python项目实战——西游记用字统计

项目来自于https://github.com/Honlan/fullstack-data-engineer

本文用到的xyj.txt也可以在本github修改,唯一不同的地方是作者使用是python2来进行统计,改成Python3,有几处细节还是听不一样的,但是结果是一样的,主要是汉字编码以及xrange部分,本代码主要做的事情为:

  • 统计书本中出现多少个不同的汉字
  • 每个汉字的出现次数以及对应频次
  • 按照出现频次对汉字进行排序并且存储到txt中

 

步骤如下:

  1. 读取xyj.txt
  2. 分别准备list和dict记录出现的汉字和汉字及其频次
  3. 遍历txt的每一行进行统计,去除标点符号和特殊字符
  4. 将统计结果排序
  5. 将结果写入csv文件(写入TXT也可以)
  6. 关闭文件

 

代码如下:

 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的运行结果)

 

完整内容可以去这里下载:

https://files.cnblogs.com/files/dapeng-bupt/xyj.zip

posted @ 2019-02-15 17:45  皇家大鹏鹏  阅读(795)  评论(0编辑  收藏  举报