我正在寻找一种使用PHP在文本体中查找常用短语的方法。如果在php中不可能,我会对其他可以帮助我完成此操作的网络语言感兴趣。
内存或速度不是问题。
现在,我可以轻松找到关键字,但不知道如何搜索短语。
答案 0 :(得分:3)
我编写了一个PHP脚本来完成这项工作,right here.它首先将源文本拆分为一个单词数组及其出现次数。然后,它计算具有指定参数的那些单词的常见序列。这是旧代码,没有评论,但也许你会发现它很有用。
答案 1 :(得分:1)
只使用PHP?我能想到的最直接的是:
我对正式的CS很不满意,但我认为这是n^2
复杂性,特别是在最坏的情况下涉及n(n-1)/2
比较。我毫不怀疑有一些更好的方法可以做到这一点,但你提到效率是一个非问题,所以这样做。
代码如下(我使用了一个新功能,array_keys接受搜索参数):
// assign the source text to $text
$text = file_get_contents('mytext.txt');
// there are other ways to do this, like preg_match_all,
// but this is computationally the simplest
$phrases = explode('.', $text);
// filter the phrases
// if you're in PHP5, you can use a foreach loop here
$num_phrases = count($phrases);
for($i = 0; $i < $num_phrases; $i++) {
$phrases[$i] = trim($phrases[$i]);
}
$counts = array();
while(count($phrases) > 0) {
$p = array_shift($phrases);
$keys = array_keys($phrases, $p);
$c = count($keys);
$counts[$p] = $c + 1;
if($c > 0) {
foreach($keys as $key) {
unset($phrases[$key]);
}
}
}
print_r($counts);
查看实际操作:http://ideone.com/htDSC
答案 2 :(得分:1)
我认为你应该选择
$str = "Hello friend, you're
looking good today!";
print_r(str_word_count($str, 1));
将给出
Array
(
[0] => Hello
[1] => friend
[2] => you're
[3] => looking
[4] => good
[5] => today
)
然后您可以使用array_count_values()
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
会给你
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
答案 3 :(得分:0)
一个丑陋的解决方案,因为你说丑陋可以,就是为你的任何一个短语搜索第一个单词。然后,一旦找到该单词,检查它后面的下一个单词是否与短语中的下一个预期单词匹配。这将是一个循环,只要命中为正,直到一个单词不存在或短语完成,它将继续运行。
简单,但非常丑陋,可能非常非常慢。
答案 4 :(得分:0)
来晚了,但是由于我在做类似事情时偶然发现了这一点,所以我想分享一下我在2019年登陆的地方:
https://packagist.org/packages/yooper/php-text-analysis
这个库使我的任务变得微不足道。就我而言,我有一系列搜索短语,这些单词最终分解为单个术语,然后进行归一化,然后创建两个和三个单词的ngram。遍历生成的ngram,我可以轻松地总结出特定短语的出现频率。
$words = tokenize($searchPhraseText);
$words = normalize_tokens($words);
$ngram2 = array_unique(ngrams($words, 2));
$ngram3 = array_unique(ngrams($words, 3));
非常酷的图书馆,提供了很多东西。
答案 5 :(得分:-2)