【发布时间】:2015-01-26 02:24:00
【问题描述】:
我是 python 新手,正在尝试对列表进行排序并获取 3 个最常用的单词。我已经到这一步了:
from collections import Counter
reader = open("longtext.txt",'r')
data = reader.read()
reader.close()
words = data.split() # Into a list
uniqe = sorted(set(words)) # Remove duplicate words and sort
for word in uniqe:
print '%s: %s' %(word, words.count(word) ) # words.count counts the words.
这是我的输出,我怎样才能对最常用的词进行排序并只列出第一个、第二个和第三个常用词?:
2: 2
3.: 1
3?: 1
New: 1
Python: 5
Read: 1
and: 1
between: 1
choosing: 1
or: 2
to: 1
【问题讨论】:
-
你的方法有一个缺陷:你不必为了得到三个最常用的词而对这个列表进行排序。
-
为什么要对单词进行排序以及为什么要删除重复项?
标签: python list python-2.7 frequency