【发布时间】:2021-09-27 09:46:08
【问题描述】:
我正在使用此代码来计算文本文件中的相同单词。
filename = input("Enter name of input file: ")
file = open(filename, "r", encoding="utf8")
wordCounter = {}
with open(filename,'r',encoding="utf8") as fh:
for line in fh:
# Replacing punctuation characters. Making the string to lower.
# The split will spit the line into a list.
word_list = line.replace(',','').replace('\'','').replace('.','').replace("'",'').replace('"','').replace('"','').replace('#','').replace('!','').replace('^','').replace('$','').replace('+','').replace('%','').replace('&','').replace('/','').replace('{','').replace('}','').replace('[','').replace(']','').replace('(','').replace(')','').replace('=','').replace('*','').replace('?','').lower().split()
for word in word_list:
# Adding the word into the wordCounter dictionary.
if word not in wordCounter:
wordCounter[word] = 1
else:
# if the word is already in the dictionary update its count.
wordCounter[word] = wordCounter[word] + 1
print('{:15}{:3}'.format('Word','Count'))
print('-' * 18)
# printing the words and its occurrence.
for word,occurance in wordCounter.items():
print(word,occurance)
我需要它们按从大到小的顺序作为输出。例如:
单词 1:25
单词 2:12
单词 3: 5 . . .
我还需要将输入作为“.txt”文件获取。如果用户写了任何不同的东西,程序必须得到一个错误,如“写一个有效的文件名”。
如何同时对输出进行排序和生成错误代码?
【问题讨论】:
-
输入的输入必须以“.txt”结尾。这里的主要目标是不允许其他任何事情。名字并不重要。
-
为什么不使用
collections中的Counter类?它更快,甚至还有一个most_common方法,可以根据需要对元素进行排序
标签: python sorting python-3.8 word-count