項目來自於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的運行結果)函數
完整內容能夠去這裏下載:編碼