【问题标题】:Searching a text for predefined words在文本中搜索预定义的单词
【发布时间】:2011-09-16 07:13:46
【问题描述】:

您好,我有一个如下所示的数据库表

word_id int(10)
word varchar(30)

我有一个文本,我想看看该文本中的哪个单词在该表中定义,这样做最优雅的方式是什么?

目前我在数据库中查询所有单词,然后使用PHP搜索整个文本中的每个单词,因此PHP从数据库中下载所有单词需要很长时间,然后它会检查每个单词他们反对我的文字。

【问题讨论】:

  • 您是否考虑过将文本拆分为单词并在数据库中搜索每个单词(与您当前的方法相反)?这样会更有效率。
  • 使用现有的搜索引擎怎么样?有几个开源选项。你可以修改代码来查询你的数据库。
  • 无论你做什么,都要小心杂乱无章的问题。 (thedailywtf.com/Articles/The-Clbuttic-Mistake-.aspx)

标签: php mysql full-text-search data-mining


【解决方案1】:

您可以尝试提取文本中的单词并将它们放入 SELECT 查询中,如下所示:

$words = array_unique(get_words_in_text(...));
$sql = "SELECT * FROM words WHERE word IN (".implode(", ", $words)).")";

可能是您的 SQL 引擎优化了此语句。在任何情况下,数据库连接的使用率都低于您当前的方法。

您也可以尝试临时创建一个单独的单词表,并将文本中的所有单词添加到该表中。然后您可以使用主词表执行JOIN。如果两个表都被正确索引,这可能会相当快。

编辑: 这个问题/答案表明创建临时表确实更快(请参阅 cmets):mysql select .. where .. in -> optimizing。但是,这当然取决于您使用的具体数据库、单词表的大小、文本的大小和索引的配置。因此,我建议针对您的特定场景评估这两种方法。请报告你的结果。 :-)

【讨论】:

    【解决方案2】:

    一个想法:

    // get words in file into array
    $file = file_get_contents('file.txt', FILE_IGNORE_NEW_LINES);
    $file_words = explode(" ", $file);
    
    // remove duplicate words, count elements in array after de-duplication
    $file_words = array_unique($file_words);
    $file_count = count($file_words);
    
    // create empty array in which to store hits
    $words_with_definition = array();
    
    // check to see if each word exists in database
    for ($i=0; $i < $file_count; $i++)
    {
        // intentionally leaving out db connection, this is just a concept
        // word should be at least three characters, change as needed
        if (strlen($file_words[$i]) >= 3)
        {
            $sql = "SELECT word FROM your_table WHERE word='".$file_words[$i]."'";
    
            if (mysql_num_rows($sql) > 0)
            {
                // this is a hit, add it to $words_with_definition
                array_push($words_with_definition, $file_words[$i]);
            }
        }
    }
    

    $words_with_definition 数组中的任何内容都将是数据库中的单词。

    【讨论】:

      猜你喜欢
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-22
      • 2011-12-06
      • 1970-01-01
      相关资源
      最近更新 更多