文件中最常出现的单词的数组,以换行符分隔。
如何从由换行符 (\n) 分隔的文件中获取最常出现的单词数组?
示例文件:
person
person
dog
cat
person
lemon
orange
person
cat
dog
dog
文件中的单词没有特定的顺序。
我怎样才能让它表现得像下面这样?
回显$顶部[0]; //输出:人
回显 $top[1]; //输出:狗
等等...
提前致谢!
How would I get an array of the top occurring words out of a file separated by newlines (\n)?
Example file:
person
person
dog
cat
person
lemon
orange
person
cat
dog
dog
The words in the file are in no particular order.
How would I make it behave like the following?
echo $top[0]; //output: person
echo $top[1]; //output: dog
etc...
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
http://php.net/array_count_values
演示:http://ideone.com/zd82W
要从结果数组中获取第一个元素(出现次数最多的单词),您可以执行以下操作:
演示:http://ideone.com/A0WPa
http://php.net/array_count_values
Demo: http://ideone.com/zd82W
To get the first element (word which occurs the most) from the resulting array, you can do this:
Demo: http://ideone.com/A0WPa
我可能会使用这样的方法:
没有真正测试过,但我想这样的东西应该有效:
(如果您的文件很大:不需要将整个文件加载到内存中)
现在,
$words
数组中的第一个键是最常用的单词——对应的值是单词的数量在您的文件中出现过多次。I would probably use something like this :
Not really tested, but something like this should work, I suppose :
(should work better than
array_count_values()
if your file is big : no need to load the whole file into memory)Now, the first key in the
$words
array is the most used word -- and the corresponding value is the number of times it's been seen in your file.