我使用这个代码来计算文本文件中的相同单词
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”文件的形式获取输入。如果用户写入任何不同的内容,则程序必须得到一个错误,即“写入有效的文件名”
如何对输出进行排序并同时生成错误代码
您可以尝试:
并重复输入命令
对于按顺序打印,您可以在打印之前按引用对其进行排序,如下所示:
<>为了检查文件是否以你想要的方式有效,你可以考虑使用:相关问题 更多 >
编程相关推荐