在自然語言處理中,很常見的是要對文本數據進行分詞處理。博主是代碼小白,目前只是用python作為數據預處理的工具,而按照結巴中文分詞的導語:做最好的python中文分詞組件“jieba”。因而博主也就在本人的機子上安裝了 ubuntu+python2.7+jieba組成的分詞組合。
關於安裝的博客已經很多了,我把安裝好后我自己寫的中文分詞代碼貼出來。
一般情況下,做中文分詞之后就會去停用詞,所以我直接寫到了同一個py文件中。
文件的第五行:自定義的用戶詞典位置
文件的第十行:停用詞詞典的位置,自己也可以添加和修改
同理,第11和第18行分別是讀取和保存文件。
1 #coding=utf-8 2 import jieba 3 import sys 4 sys.path.append("../") 5 jieba.load_userdict("/。。。/user_dict.txt") 6 import jieba.posseg as pseg 7 import time 8 t1=time.time() 9 10 stopwords = {}.fromkeys([ line.rstrip() for line in open('/。。。。。/stopwords.txt') ]) 11 f=open("/。。。/test.txt","r") #讀取文本 12 txtlist=f.read().decode('utf-8') 13 words=jieba.cut(txtlist) 14 for w in words: 15 seg=str(w.word.encode('utf-8')) 16 if seg not in stopwords: 17 result+=str(seg)+" "#+"/"+str(w.flag)+" " #去停用詞 18 f=open("/..../result.txt","a") #將結果保存到另一個文檔中 19 f.write(result) 20 21 f.close() 22 t2=time.time() 23 print("分詞及詞性標注完成,耗時:"+str(t2-t1)+"秒。") #反饋結果