0
我有这个代码来搜索文本文件中的5个最常见的单词,但我不能在程序结束时使用排序和反向功能...我将如何避免使用他们?在文本文件python中的5个最常见的单词
words = open('romeo.txt').read().lower().split()
uniques = []
for word in words:
if word not in uniques:
uniques.append(word)
counts = []
for unique in uniques:
count = 0
for word in words:
if word == unique:
count += 1
counts.append((count, unique))
counts.sort()
counts.reverse()
for i in range(min(5, len(counts))):
count, word = counts[i]
print('%s %d' % (word, count))
我认为当你使用排序,你应该扭转之前保存结果,所以'counts.sort()'不更新计数 – d3r1ck
计数(或排序)之前,你可能要“正常化'的话。小写?德变复数?删除动词结尾? –