如何解决如何使用 Python 对字数进行排序?
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('?','').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”文件获取。如果用户写了任何不同的东西,程序必须得到一个错误“写一个有效的文件名”。
解决方法
为了按顺序打印,您可以在打印之前按这样的出现对它们进行排序:
for word,occurance in sorted(wordCounter.items(),key=lambda x: x[1],reverse=True):
print(word,occurance)
为了以您想要的方式检查文件是否有效,您可以考虑使用:
import os
path1 = "path/to/file1.txt"
path2 = "path/to/file2.png"
if not path1.lower().endswith('.txt'):
print("Write a valid file name")
if not os.path.exists(path1):
print("File does not exists!")
,
你可以试试:
if ( filename[-4:0] != '.txt'):
print('Please input a valid file name')
并重复输入命令...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。