编程语言
首页 > 编程语言> > Python专栏|大题精讲:统计文件中中文字符字频

Python专栏|大题精讲:统计文件中中文字符字频

作者:互联网

题目如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

==================================================================

知识点:
※ strip()
※ 字典计数:dic[key]=dic.get(key,0)+1

#图片一对应代码
f.open("命运.txt","r",encoding="utf-8")
txt = f.read()
for ch in ",。:?!":
    txt = txt.replace(ch,"")

d={}

for ch in txt:
    d[ch]=d.get(ch,0)+1

ls = list(d.items())

ls.sort(key = lambda x:x[1],reverse = True)
print("{}:{}".format(ls[0][0],ls[0][1]))

#图片二对应代码
f.open("命运.txt","r",encoding="utf-8")
txt = f.read()
txt = txt.replace("\n","")

d={}

for ch in txt:
    d[ch]=d.get(ch,0)+1

ls = list(d.items())

ls.sort(key = lambda x:x[1],reverse = True)
for i in range(10):
    print(ls[i][0],end = "")#让他不要输出一行就回车
#第三张图片
f.open("命运.txt","r",encoding="utf-8")
txt = f.read()
txt = txt.replace("\n","")
txt = txt.replace(" ","")
d={}
for ch in txt:
    d[ch]=d.get(ch,0)+1

ls = list(d.items())

ls.sort(key = lambda x:x[1],reverse = True)
str1 = ""
for item in ls:
    str1 = str1+item[0]+":"+str(item[1])+","

str1 = str1.strip(",")
f= open("命运-频次排序.txt","w","utf-8")
f.write(str1)
f.close()

★ B站视频讲解一
★ B站视频讲解二

标签:ch,key,Python,精讲,ls,字频,txt,open,str1
来源: https://blog.csdn.net/weixin_44840172/article/details/110382792