直入正题、具体实现如下:
# 打开文件
fr = open('C:/Users/Mr.R/Desktop/1.txt', 'r', encoding='UTF-8')
# 读取文件所有行
content = fr.readlines()
contentLines = ''
characers = []
stat = {}
# 依次迭代所有行
for line in content:
# 去除空格
line = line.strip()
if len(line) == 0:
continue
contentLines = contentLines + line
# print(line)
# 统计每一字出现的个数
for x in range(0, len(line)):
# 如果字符第一次出现 加入到字符数组中
if not line[x] in characers:
characers.append(line[x])
# 如果是字符第一次出现 加入到字典中
if line[x] not in stat:
stat[line[x]] = 1
# 出现次数加一
stat[line[x]] += 1
# 对字典进行倒数排序 从高到低 其中e表示dict.items()中的一个元素,
# e[1]则表示按 值排序如果把e[1]改成e[0],那么则是按键排序,
# reverse=False可以省略,默认为升序排列
stat = sorted(stat.items(), key=lambda e: e[1], reverse=True)
# 打印stat 每个字和其出现的次数 stat经过排序后变成二元组
# print(stat)
# for i in range(len(stat)):
# print(stat[i][0],stat[i][1])
for i in stat:
print(i[0], i[1])
print('全文共有%d个字' % len(contentLines))
print('一共有%d个不同的字' % len(characers))
fr.close()
原数据是:
image.png
得到的结果为:
image.png