现在我的代码打印了txt文件中每个单词的使用次数。我试图让它只打印txt文件中使用大写字母的前三个单词...
file=open("novel.txt","r+")
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for a,b in wordcount.items():
print (b, a)
答案 0 :(得分:0)
首先,您希望使用str.istitle()
将结果限制为大写单词:
file=open("novel.txt","r+")
wordcount={}
for word in file.read().split():
if word.istitle():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for a,b in wordcount.items():
print (b, a)
然后sort the results使用sorted()
并打印出前三个:
file=open("novel.txt","r+")
wordcount={}
for word in file.read().split():
if word.istitle():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
items = sorted(wordcount.items(), key=lambda tup: tup[1], reverse=True)
for item in items[:3]:
print item[0], item[1]
答案 1 :(得分:-1)
在Collections
中,有一个Counter
课程。 https://docs.python.org/2/library/collections.html。
cnt = Counter([w for w in file.read().split() if w.lower() != w]).most_common(3)