使用python排序单词频率计数 [英] Sorted Word frequency count using python
本文介绍了使用python排序单词频率计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须使用python计算文本中的单词频率.我想到了将单词保留在字典中,并对每个单词进行计数.
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 ?
推荐答案
您可以使用同一词典:
>>> d = { "foo": 4, "bar": 2, "quux": 3 }
>>> sorted(d.items(), key=lambda item: item[1])
第二行打印:
[('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])]
该行打印:
['bar', 'quux', 'foo']
这篇关于使用python排序单词频率计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文