python进行中文字频、高频字覆盖率统计
题目:用python统计《孟子》总体长度、字种、字频、高频字覆盖率。
《孟子》全文下载:点击下载
高频字:字频>=500的字
本题有三个地方要注意:
1、《孟子》中含有大量的标点符号,统计时应该把它们排除在外。
2、统计字频、高频字覆盖率是难点。
3、如何用相对直观、好看的方式打印输出结果。
源代码:
#《孟子》总体长度
f = open('ex_menzi.txt', 'r', encoding='utf-8')
text=f.read()
for ch in "《》,。:!‧「」『』〈〉;﹖.! \n?":
text = text.replace(ch, "") # 去掉文章的标点符号
print("《孟子》的总体长度:", len(text))
#《孟子》字种
result = set(text)
print("《孟子》的字种:\n", result)
print("《孟子》的字种总长:", len(result))
#《孟子》字频
my_dict={}
for char in text:
if char in my_dict:
my_dict[char] = my_dict[char]+1
else:
my_dict[char] = 1
#《孟子》高频字的覆盖率
rate = {} # 创建字典,储存每个高频字及其对应的覆盖率
number = 0 # 统计所有高频字出现的总次数
for word in my_dict.keys():
if my_dict.get(word, 0) >= 500: # 高频字字频>=500
rate[word] = my_dict.get(word, 0)/len(text)
number = number + my_dict.get(word, 0)
else:
continue
# 输出高频字覆盖率
items = list(rate.items()) # 返回所有的键值对
print("每个高频字的覆盖率如下:")
for i in range(len(items)):
word, count = items[i]
print(word, " ", '%.2f%%' % (count * 100)) # 打印每个高频字及其覆盖率
print("高频字总覆盖率是:")
print('%.2f%%' % (number/len(text) * 100)) # 打印高频字的总覆盖率
代码运行后的结果: