我知道如何使用爆炸和某些数组函数在文本中获得单词频率,但我真正想要的是获得2个单词或更多的频率。例如:
“这是一个示例文本,它是一个用于教育目的的示例文本。”如何在文本中获得单词频率
我需要的代码来做到这一点:
是(2)
示例文本(2)
样本(2)
....等等
在此先感谢。
我知道如何使用爆炸和某些数组函数在文本中获得单词频率,但我真正想要的是获得2个单词或更多的频率。例如:
“这是一个示例文本,它是一个用于教育目的的示例文本。”如何在文本中获得单词频率
我需要的代码来做到这一点:
是(2)
示例文本(2)
样本(2)
....等等
在此先感谢。
下面的代码将获得2个连续话:
$string = 'This is a sample text. It is a sample text made for educational purposes. This is a sample text. It is a sample text made for educational purposes.';
$sanitized = $even = preg_replace(array('#[^\pL\s]#', '#\s+#'), array(' ', ' '), $string); // sanitize: only letters, replace multiple whitespaces with 1
$odd = preg_replace('#^\s*\S+#', '', $sanitized); // Remove the first word
preg_match_all('#\S+\s\S+#', $even, $m1); // Get 2 words
preg_match_all('#\S+\s\S+#', $odd, $m2); // Get 2 words
$results = array_count_values(array_merge($m1[0], $m2[0])); // Merge results and count
print_r($results); // printing
输出:
Array
(
[This is] => 2
[a sample] => 4
[text It] => 2
[is a] => 4
[sample text] => 4
[made for] => 2
[educational purposes] => 2
[It is] => 2
[text made] => 2
[for educational] => 2
[purposes This] => 1
)
一个改进是转换字符串为小写?
我让其余的给你弄清楚:-)
完美!你是非常感谢你的人! – dxer
顺便说一下,你有什么方法可以扩展这段代码,这样它可以得到3个或更多的单词吗?此外,我不明白背后的奇数和偶数的概念,如果你解释我的逻辑将是伟大的。 – dxer
@dxer哦,是的,你可以将它改为3个单词,但是你必须重写正则表达式,或者添加另外的(也许很少)行。 “奇数”和“偶数”的概念最好用一个例子来说明:假设我有'a b a b'。我们有'a b' x2和'b a' x1。我们的正则表达式检查'word space word',问题是当正则表达式匹配'a b'时会进一步移动,所以'b a'不会匹配。当它进一步移动时,第二部分将匹配'a b'。 – HamZa
一些伪代码,让您开始:
frequencies = empty array
words = explode sentence on white spaces
for each word in words :
sanitized word = trim word and convert to lower case
frequency[ sanitized word ] ++
endforeach
的frequency
数组现在包含的次一个字出现在句子的数量。
这不是我的意思,这只能得到一个字的频率,我正在寻找的是2个字的频率 – dxer
显示一些努力:你有什么尝试? –
@MarvinLabs我会如果我能这就是为什么我寻求帮助,所以如果你可以添加一些东西,这将是件好事。 – dxer
请参阅[我应避免询问什么类型的问题?](http://stackoverflow.com/help/dont-ask)。 – budwiser