在NLP中,很多都要對字或者單詞進行預處理,或者是要建立詞典;
例如:tf1: nn實作評論分類
例如:15. tf13: 簡單聊天機器人
上面兩篇都是對單詞的操作,下面提供一份python3下對漢字的操作;
代碼中有注釋:
import sys
fr = open('xyj.txt', 'r', encoding='UTF-8')
characters = []
stat = {}
for line in fr:
# 去掉每一行兩邊的空白
line = line.strip()
# 如果為空行則跳過該輪循環
if len(line) == 0:
continue
# 将文本轉為unicode,便于處理漢字
line = str(line)
# print (line)
# 周遊該行的每一個字
for x in range(len(line)):
# 去掉标點符号和空白符
if line[x] in [' ', '\t', '\n', '。', ',', '(', ')', '(', ')', ':', '□', '?', '!', '《', '》', '、', ';', '“', '”', '……']:
continue
# 尚未記錄在characters中
if not line[x] in characters:
characters.append(line[x])
# 尚未記錄在stat中
if not line[x] in stat:
stat[line[x]] = 0
# 漢字出現次數加1
stat[line[x]] += 1
print (len(characters))
print (len(stat))
def dict2list(dic:dict):
''' 将字典轉化為清單 '''
keys = dic.keys()
vals = dic.values()
lst = [(key, val) for key, val in zip(keys, vals)]
return lst
# lambda生成一個臨時函數
# d表示字典的每一對鍵值對,d[0]為key,d[1]為value
# reverse為True表示降序排序
stat = sorted(dict2list(stat), key=lambda d:d[1], reverse=True)
fw = open('result.csv', 'w', encoding='UTF-8')
for item in stat:
# 進行字元串拼接之前,需要将int轉為str
# 字典的周遊方式: fw.write(item + ',' + str(state[item]) + '\n')
# 排完序後是清單
fw.write(item[0] + ',' + str(item[1]) + '\n')
fr.close()
fw.close()
print ("success!")
複制