php - 文本语料库中的单词匹配非常慢

标签 php mysql sql lookup words

我有两张 table 。在表 1 中,我有大约 400K 行,每行包含一段文本,最多可以包含 50 个句子。在表 2 中,我有一个包含 80k 个单词的词典以及我需要对每个段落的每个单词进行编码的分数。

我的 PHP 脚本的全部要点是根据需要将每一段文本分解成尽可能多的单词,然后在词典中查找每个单词的得分是多少,最后计算所有单词的总分每行。

到目前为止,我的策略是创建一个执行以下操作的脚本:

  1. 连接到数据库,表 1
  2. While循环,一行接一行
  3. 对于当前行,分解段落。
  4. 对于每个单词,如果该单词存在则查找表 2 并返回分数。
  5. 最后得到当前行的总分。
  6. 用当前段落的总分更新表 1。
  7. 回到第 2 点。

我的代码有效但效率不高。问题是脚本太慢了,让它运行一个小时只会计算前 500 行。这是个问题,因为我有 40 万行。我将需要此脚本用于其他项目。

你会建议我做什么来降低这个过程的强度?

<?php

//Include functions
        include "functions.php";
        ini_set('max_execution_time', 9000000);
        echo 'Time Limit = ' . ini_get('max_execution_time');
        $db='senate';   
//Function to search into the array lexicon     
        function searchForId($id, $array) {
        foreach ($array as $key2 => $val) {
        if ($val['word'] === $id) {
        return $key2;
       } 
   }
   return null;
}       

// tags to remove
        $remove   = array('{J}','{/J}','{N}','{/N}','{V}','{/V}','{RB}','{/RB}');       
        $x=1;
//Conecting the database
        if (!$conn) {
        die('Not connected : ' . mysql_error());}


// Choose the current db
        mysql_select_db($db);

//Slurps the lexicon into an array
$sql = "SELECT word, score FROM concreteness";
$resultconcreteness = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($resultconcreteness)) {
$array[] = $row;
}

//loop      
        while($x<=500000) {
        $data = mysql_query("SELECT `key`, `tagged` FROM speechesLCMcoded WHERE `key`='$x'") or die(mysql_error());

// puts the "data" info into the $info array 
        $info = mysql_fetch_array( $data);
        $tagged=$info['tagged'];
        unset($weight);
        unset($count);
        $weight=0;
        $count=0;

// Print out the contents of the entry 
        Print "<b>Key:</b> ".$info['key'] .  " <br>";

// Explodes the sentence
        $speech = explode(" ", $tagged);

// Loop every word  
        foreach($speech as $word) {

//Check if string contains our tag

if(!preg_match('/({V}|{J}|{N}|{RB})/', $word, $matches)) {} else{

//Removes our tags
        $word = str_replace($remove, "", $word);

        $id = searchForId($word, $array);
//      print "ID: " . $id . "<br>";
//      print "Word: " . $array[$id]['word'] . "<br>";
//      print "Score: " . $array[$id]['score'] . "<br>";
        $weight=$weight+$array[$id]['score'];
        $count=$count +1;
//      print "Weight: " . $weight . "<br>";
 //     print "Count: " . $count . "<br>";
        }
}
        $sql = "UPDATE speechesLCMcoded SET weight='$weight', count='$count' WHERE `key`='$x';" ;
        $retval = mysql_query( $sql, $conn );
        if(! $retval )
        {die('Could not update data: ' . mysql_error());}
        echo "Updated data successfully\n";
        ob_flush();
        flush();   

        //Increase the loop by one
        $x=$x+1;

}?>

这是索引:

CREATE TABLE `speechesLCMcoded` (
 `key` int(11) NOT NULL AUTO_INCREMENT,
 `speaker_state` varchar(100) NOT NULL,
 `speaker_first` varchar(100) NOT NULL,
 `congress` varchar(100) NOT NULL,
 `title` varchar(100) NOT NULL,
 `origin_url` varchar(100) NOT NULL,
 `number` varchar(100) NOT NULL,
 `order` varchar(100) NOT NULL,
 `volume` varchar(100) NOT NULL,
 `chamber` varchar(100) NOT NULL,
 `session` varchar(100) NOT NULL,
 `id` varchar(100) NOT NULL,
 `raw` mediumtext NOT NULL,
 `capitolwords_url` varchar(100) NOT NULL,
 `speaker_party` varchar(100) NOT NULL,
 `date` varchar(100) NOT NULL,
 `bills` varchar(100) NOT NULL,
 `bioguide_id` varchar(100) NOT NULL,
 `pages` varchar(100) NOT NULL,
 `speaker_last` varchar(100) NOT NULL,
 `speaker_raw` varchar(100) NOT NULL,
 `tagged` mediumtext NOT NULL,
 `adjectives` varchar(10) NOT NULL,
 `verbs` varchar(10) NOT NULL,
 `nouns` varchar(10) NOT NULL,
 `weight` varchar(50) NOT NULL,
 `count` varchar(50) NOT NULL,
 PRIMARY KEY (`key`)
) ENGINE=InnoDB AUTO_INCREMENT=408344 DEFAULT CHARSET=latin1

最佳答案

您有一个相当小的引用表(您的词典)和一个巨大的文本语料库(表 1)。

如果我是你,我会通过从表中读取整个词典到内存中的 php 数组来启动你的程序。即使您所有的单词都是 20 个字符的长度,这也只需要十几兆字节的 RAM。

然后通过在内存中查找单词而不是使用 SQL 查询来执行第 4 步。您的内部循环(针对每个单词)会更快,并且同样准确。

不过,请注意一件事。如果要复制 MySQL 的不区分大小写的查找行为,则需要通过将它们转换为小写来规范化词典中的单词。

看到你的代码后编辑

一些专业提示:

  • 适本地缩进代码,这样您就可以一目了然地看到循环的结构。
  • 请记住,将数据传递给函数需要时间。
  • PHP 数组是关联的。你可以做 $value = $array[$key]。这很快。您不必线性搜索数组。您正在每个单词一次!!
  • 准备好的陈述很好。
  • 当您可以从结果集中读取下一行时重复 SQL 语句是不好的。
  • 流式结果集很好。
  • mysql_ 函数调用集被其开发人员和其他所有人弃用和鄙视,这是有充分理由的。

你的循环中发生了太多事情。

你需要的是:

首先,从使用mysql_ 接口(interface)切换到使用mysqli_。去做就对了。 mysql_ 太慢、太旧、太笨拙。

$db = new mysqli("host", "user", "password", "database");

其次,改变加载词典的方式,以优化整个关联数组处理。

$lookup = array();
//Slurps the lexicon into an array, streaming it row by row
$sql = "SELECT word, score FROM concreteness";
$db->real_query($sql) || die $db->error;
$lkup = $db->use_result();
while ($row = $lkup->fetch_row()) {
      $lookup[strtolower($row[0])] = $row[1];
}
$lkup->close();

这为您提供了一个名为 $lookup 的关联数组。如果你有一个$word,你可以通过这种方式找到它的权重值。这很快。您的示例代码中的内容非常慢。请注意,在创建键和查找单词时,键都被转换为小写。出于性能原因,如果可以避免,请不要将它放在函数中。

if (array_key_exists( strtolower($word), $lookup )) {
    $weight += $lookup[strtolower($word)]; /* accumulate weight */
    $count ++;                             /* increment count   */
}
else {
  /* the word was not found in your lexicon. handle as needed */
}

最后,您需要优化对文本语料库行的查询及其更新。我相信您应该使用准备好的语句来做到这一点。

这是如何进行的。

在程序的开头附近放置此代码。

$previouskey = -1;
if (/* you aren't starting at the beginning */) {
   $previouskey = /* the last successfully processed row */
}

$get_stmt = $db->prepare('SELECT `key`, `tagged` 
                           FROM speechesLCMcoded 
                          WHERE `key` > ?
                          ORDER BY `key` LIMIT 1' );

$post_stmt = $db->prepare ('UPDATE speechesLCMcoded 
                               SET weight=?, 
                                   count=? 
                             WHERE `key`=?' );

这些为您提供了两个随时可用的处理语句。

请注意,$get_stmt 检索您尚未处理的第一个 key。即使您丢失了一些 key ,这也会起作用。总是好的。这将非常有效,因为您在 key 列上有一个索引。

所以这就是你的循环最终的样子:

 $weight = 0;
 $count = 0;
 $key = 0;
 $tagged = '';

 /* bind parameters and results to the get statement */
 $get_stmt->bind_result($key, $tagged);
 $get_stmt->bind_param('i', $previouskey);

 /* bind parameters to the post statement */
 $post_stmt->bind_param('iii',$weight, $count, $key);

 $done = false;
 while ( !$done ) {
    $get_stmt->execute();
    if ($get_stmt->fetch()) {

        /* do everything word - by - word  here on the $tagged string */

        /* do the post statement to store the results */
        $post_stmt->execute();

        /* update the previous key prior to next iteration */
        $previouskey = $key; 
        $get_stmt->reset();
        $post_stmt->reset();
    } /* end if fetch */
    else {
       /* no result returned! we are done! */
       $done = true;
    }
 } /* end while not done */

这应该可以让您将每行的处理速度降到亚秒级。

关于php - 文本语料库中的单词匹配非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23555694/

相关文章:

php - PHP 实际使用了多少内存?

javascript - APEX:如何实现循环级联选择列表(多对多)

php - 如何检索多列的总和?代码点火器

PHP 获取包含子目录的文件列表

php - Laravel 4 Eloquent 返回错误的 ID

php - 如何生成与数据库记录匹配的唯一 URL 变量?

mysql - 这个mysql触发器有什么问题吗?

mysql - 另一个查询中的 ExpressionEngine 查询结果

sql - 如何从表中删除重复添加的日志?

sql - UTC 时间到本地时区(中部时间)转换 MS SQL Server