Python统计txt文档中每个字符出现的次数!
txt文档内容
python代码
from collections import Counter
txt = open('./ReadData/你的答案.txt','r',encoding='utf-8').read()
for s in ",。: 《 》 \n":
txt=txt.replace(s,"")
def count_char1():
count ={}
for i in txt:
if i not in count:
count[i]=1
else:
count[i]=count[i]+1
print("直接计算每个字符出现的次数:",count)
def count_char2():
count1 =Counter(txt)
print("调用Counter()计算每个字符出现的次数:",count1)
def count_char3():
count2 ={}
for char in txt:
count2.setdefault(char,0)
count2[char]+=1
print("调用setdefault():计算每个字符出现的次数:",count2)
if __name__ =='__main__':
count_char1()
count_char2()
count_char3()
结果展示