我想将一个句子解析成单词,但有些句子有两个单词,可以组合成一个单词并产生不同的含义。
例如:
Eminem is a hip hop star.
如果我通过按空格拆分单词来解析它,我将得到
Eminem
is
a
**hip**
**hop**
star
但我想要这样的东西:
Eminem
is
a
**hip hop**
star
这只是一个例子;可能有一些其他的单词组合被列为字典中的单词。
我怎样才能轻松地解析它?
我在 MySQL 数据库中有一本字典。是否有任何 API 可以执行此操作?
最佳答案
没有我所知道的 API。但是,您可以尝试 SQL like 子句。
$words = explode(' ', 'Eminem is a hip hop star');
$len = count($words);
$fixed = array();
for($x = 0; $x < $len; $x++) {
//LIKE 'hip %' will match hip hop
$q = mysql_query("SELECT word FROM dict WHERE word LIKE '".$words[$x]." %'");
//Combine current and next word
$combined = $words[$x].' '.$words[($x+1)];
while( $result = mysql_fetch_array($q)) {
if($result['word'] == $combined) { //Word is in dictionary
$fixed[] = $combined;
$x++;
} else { //Word isn't in dictionary
$fixed[] = $words[$x];
}
}
}
*请原谅我缺少 PDO。我现在很懒。
编辑:我做了一些思考。虽然上面的代码不是最佳的,但我提出的优化版本可能不会做得更好。事实上,无论您如何处理问题,您都需要将输入句子中的每个单词与字典进行比较,并执行额外的计算。我看到您可以根据硬件限制采取两种方法。
这两种方法都假定一个具有(示例)结构的 dict
表:
+--+-----+------+
|id|first|second|
+--+-----+------+
|01|hip |hop |
+--+-----+------+
|02|grade|school|
+--+-----+------+
选项 1:您的网络服务器有大量可用 RAM(和不错的处理器)
这里的想法是通过将字典缓存在 PHP 的内存中(使用 APC 或 memcache,如果您计划在多个服务器上运行则使用后者)来完全绕过数据库层。这会将所有负载放在您的网络服务器上,但是它可能会快得多,因为从 RAM 访问缓存数据比查询您的数据库快得多。
(同样,为了简单起见,我省略了 PDO 和 sanitizer )
// Step One: Cache Dictionary..the entire dictionary
// This could be run on server start-up or before every user input
if(!apc_exists('words')) {
$words = array();
$q = mysql_query('SELECT first, second FROM dict');
while($res = mysql_fetch_array($q)) {
$words[] = array_values($res);
}
apc_store('words', serialize($words)); //You could use memcache if you want
}
// Step Two: Compare cached dictionary to user input
$data = explode(' ', 'Eminem is a hip hop star');
$words = apc_fetch('words');
$count = count($data);
for($x = 0; $x < $count; $x++) { //Simpler to use a for loop
foreach($words as $word) { //Match against each word
if($data[$x] == $word[0] && $data[$x+1] == $word[1]) {
$data[$x] .= ' '.$word[1];
array_splice($data, $x, 1);
$count--;
}
}
}
选项 2:快速 SQL Server
第二个选项涉及从 SQL 服务器查询输入文本中的每个单词。例如,对于句子“Eminem is hip hop”,您将创建一个看起来像 SELECT * FROM dict WHERE (first = 'Eminem' && second = 'is') || 的查询(first = 'is' && second = 'hip') || (first = 'hip' && second = 'hop')
。然后要修复单词数组,您只需循环遍历 MySQL 的结果并将适当的单词融合在一起。如果你愿意走这条路,那么在查询数据库之前缓存常用词并修复它们可能会更有效。这样您就可以从查询中消除条件。
关于php - 如何用字典数据库解析一个词/短语与 2 个词(在 PHP 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7185759/