编写程序,统计文本文件“需要统计文本.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)))
 

Python学习笔记一(统计)

Python学习笔记一(统计)

Python学习笔记一(统计)

 

 

相关文章:

  • 2021-09-20
  • 2022-12-23
  • 2022-12-23
  • 2021-09-06
  • 2021-08-21
  • 2021-07-02
  • 2021-10-17
猜你喜欢
  • 2021-04-19
  • 2021-05-31
  • 2021-10-05
  • 2022-01-22
  • 2021-06-18
  • 2021-12-28
相关资源
相似解决方案