Python统计txt文档中每个字符出现的次数!

Python统计txt文档中每个字符出现的次数!

txt文档内容
Python统计txt文档中每个字符出现的次数!_第1张图片
python代码

# -*- coding: utf-8 -*-
#@Project filename:PythonDemo  统计文本中每个汉字的频率.py
#@IDE   :IntelliJ IDEA
#@Author :ganxiang
#@Date   :2020/03/06 0006 20:21

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)
        # print(count.setdefault(char,0))
        count2[char]+=1
    print("调用setdefault():计算每个字符出现的次数:",count2)
if __name__ =='__main__':
    count_char1()
    count_char2()
    count_char3()

结果展示
在这里插入图片描述

你可能感兴趣的:(PythonStudyDemo,python)