项目来自于https://github.com/Honlan/fullstack-data-engineerpython
本文用到的xyj.txt也能够在本github修改,惟一不一样的地方是做者使用是python2来进行统计,改为Python3,有几处细节仍是听不同的,可是结果是同样的,主要是汉字编码以及xrange部分,本代码主要作的事情为:git
步骤以下:github
代码以下:app
1 #!/usr/bin/env python 2 # coding:utf8 3 import sys 4 import importlib 5 importlib.reload(sys) 6 7 fr = open('xyj.txt', 'r') 8 9 characters = [] 10 stat = {} 11 12 for line in fr: 13 # 去掉每一行两边的空白 14 line = line.strip() 15 # 若是为空行则跳过该轮循环 16 17 if len(line) == 0: 18 continue 19 # 遍历该行的每个字 20 for x in range(0, len(line)): 21 # 去掉标点符号和空白符 22 if line[x] in [' ', '\t', '\n', '。', ',', '(', ')', '(', ')', ':', '□', '?', '!', '《', '》', '、', ';', '“', '”', '……']: 23 continue 24 # 还没有记录在characters中 25 if line[x] not in characters: 26 characters.append(line[x]) 27 # 还没有记录在stat中 28 if line[x] not in stat.keys(): 29 stat[line[x]] = 0 30 # 汉字出现次数加1 31 stat[line[x]] += 1 32 print(len(characters)) 33 print(len(stat)) 34 35 # lambda生成一个临时函数 36 # d表示字典的每一对键值对,d[0]为key,d[1]为value 37 # reverse为True表示降序排序 38 stat = sorted(stat.items(), key=lambda d:d[1], reverse=True) 39 40 fw = open('result.csv', 'w') 41 for item in stat: 42 # 进行字符串拼接以前,须要将int转为str 43 fw.write(item[0] + ',' + str(item[1]) + '\n') 44 fr.close() 45 fw.close()
运行结果以下:(两张图分别是写入csv的运行结果和写入TXT的运行结果)函数
完整内容能够去这里下载:编码