使用python排序词频计数 [英] Sorted Word frequency count using python

查看:36
本文介绍了使用python排序词频计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用 python 计算文本中的词频.我想把单词存入字典,并对每个单词进行计数.

现在,如果我必须根据出现次数对单词进行排序.我可以用同一个字典来做,而不是使用一个新的字典,它的键是计数,单词数组是值吗?

解决方案

可以使用同一个字典:

<预><代码>>>>d = { "foo": 4, "bar": 2, "quux": 3 }>>>sorted(d.items(), key=lambda item: item[1])

第二行打印:

[('bar', 2), ('quux', 3), ('foo', 4)]

如果您只想要一个排序的单词列表,请执行以下操作:

<预><代码>>>>[pair[0] for pair in sorted(d.items(), key=lambda item: item[1])]

该行打印:

['bar', 'quux', 'foo']

I have to count the word frequency in a text using python. I thought of keeping words in a dictionary and having a count for each of these words.

Now if I have to sort the words according to # of occurrences. Can i do it with same dictionary instead of using a new dictionary which has the key as the count and array of words as the values ?

解决方案

You can use the same dictionary:

>>> d = { "foo": 4, "bar": 2, "quux": 3 }
>>> sorted(d.items(), key=lambda item: item[1])

The second line prints:

[('bar', 2), ('quux', 3), ('foo', 4)]

If you only want a sorted word list, do:

>>> [pair[0] for pair in sorted(d.items(), key=lambda item: item[1])]

That line prints:

['bar', 'quux', 'foo']

这篇关于使用python排序词频计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆