我正在寻找一种使用PHP在正文中找到常见短语的方法。如果在php中不能做到这一点,我会对其他web语言感兴趣,这些语言可以帮助我完成这项工作。
内存或速度不是问题。
现在,我可以很容易地找到关键字,但不知道如何搜索短语。
发布于 2011-01-26 14:51:03
我已经写了一个PHP脚本来做这件事,right here.它首先将源文本分成一个单词数组和它们的出现次数。然后,它使用指定的参数对这些单词的常见序列进行计数。这是旧代码,没有注释,但也许您会发现它很有用。
发布于 2011-01-26 14:36:01
只使用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
发布于 2011-01-26 15:04:48
我觉得你应该去
str_word_count
$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
)https://stackoverflow.com/questions/4801449
复制相似问题