python 將分詞結果寫入txt文件


首先我運用的分詞工具是結巴分詞 import jieba  然后調用jieba.cut( )  但是jieba.cut 返回的是一個generator的迭代器

他可以顯示分詞結果 但是無法將結果寫入txt 各種報錯。類似於a bytes-like object is required, not 'generator'

然后我將結果進行了Str( )處理 還是報類似的錯誤 只不過變成了not ' generator'

然后經過思考我將結果作list( )處理 然后對生成的list進行處理,去' [  ' ,' ] '和' ,'

def text_save(filename,data):
    file = open(filename,'a+')
    for i in range(len(data)):
        s = str(data[i]).replace('[','').replace(']','')
        s = s.replace("'",'').replace(',','')+' '
        l = clearSen(s)
        file.write(l)
   # file.close(s)

然后可以寫進去了  但是遇到亂碼問題,寫入txt中的文本亂碼mmp。

在終端測試各個步驟的輸出結果,發現是在對list( )處理時,應該加入utf-8操作。

def text_save(filename,data):
    file = open(filename,'a+',encoding='utf-8')
    for i in range(len(data)):
        s = str(data[i]).replace('[','').replace(']','')
        s = s.replace("'",'').replace(',','')+' '
        l = clearSen(s)
        file.write(l)
   # file.close(s)

#添加句子功能
def usr_add_sentence():
    correct_sentence = entry_add.get()
    correct_sentences = list(jieba.cut(correct_sentence))
   # clearSen(correct_sentences)
    print(correct_sentences)
    text_save('./data/kenlm/2014_words.txt',correct_sentences)
    text_save('./data/kenlm/people2014_words.txt',correct_sentences)

over~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM