编写程序,统计文本文件“需要统计文本.txt”中总字符数(不包括空格及换行符)及出现的所有字符及标点符号的数量,格式:“楷:2”,字符及数量的映射换行展示,并保存到“字符统计.txt”文件中
with open(r"E:\Python\需要统计文本.txt",'r',encoding='utf-8') as f:
text = f.read()
f2 = open(r"E:\Python\字符统计.txt",'w+',encoding='utf-8')
text = text.strip() #删除字符串收尾空格及换行
text = text.replace(' ','') #删除字符串中间空格
text = text.replace('\n','')
new_txt = list(set(text)) #将字符串中字符去重得到一个新的序列
resoult = {}
f2.write("文本总字符:"+ str(len(text))+"\n")
counts = {}
for txt in new_txt:
a = text.count(txt)
w = "%s:%s"%(txt,a)
counts.setdefault(txt,a)
# print(w)
f2.write(w +"\n")
f2.close()
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)#根据字符出现的次数进行从大到小排序
print(items)
for i in range(5):
txt, count = items[i]
print("%s:%s"%(txt,str(count)))