1. 程式人生 > >使用jieba分詞並去除停用詞流程程式

使用jieba分詞並去除停用詞流程程式

準備工作

① 構建未分詞檔案、已分詞檔案兩個資料夾,將未分詞資料夾按類目定義檔名,各個類目的資料夾下可放置多個需要分詞的檔案。

② 準備一份停用詞(jieba自身應該是沒有停用詞的)

③ 根據業務需要自定義詞典(此處使用jieba自帶字典)

分詞去停詞.py

""" 
@file: 分詞去停詞.py
@Time: 2018/08/27
@Author:hnq
"""
#本程式主要用於jieba分詞,以及去除停用詞

import os
import jieba

# 儲存檔案的函式
def savefile(savepath,content):
    fp = open(savepath,'w',encoding='utf8',errors='ignore')
    fp.write(content)
    fp.close()

# 讀取檔案的函式
def readfile(path):
    fp = open(path, "r", encoding='utf8', errors='ignore')
    content = fp.read()
    fp.close()
    return content

## 去除停用詞的2個函式
# 建立停用詞list
def stopwordslist(filepath):
    stopwords = [line.strip() for line in open(filepath, 'r', encoding='utf-8').readlines()]
    return stopwords

# 對句子去除停用詞
def movestopwords(sentence):
    stopwords = stopwordslist('stop_words.txt')  # 這裡載入停用詞的路徑
    outstr = ''
    for word in sentence:
        if word not in stopwords:
            if word != '\t'and'\n':
                outstr += word
                # outstr += " "
    return outstr

if __name__ == '__main__':

    corpus_path = "語料/train/"  # 未分詞分類預料庫路徑
    seg_path = "語料/train_seg/"  # 分詞後分類語料庫路徑

    catelist = os.listdir(corpus_path)  # 獲取未分詞目錄下所有子目錄
    for mydir in catelist:
        class_path = corpus_path + mydir + "/"  # 拼出分類子目錄的路徑
        seg_dir = seg_path + mydir + "/"  # 拼出分詞後預料分類目錄
        if not os.path.exists(seg_dir):  # 是否存在,不存在則建立
            os.makedirs(seg_dir)

        file_list = os.listdir(class_path) # 列舉當前目錄所有檔案
        for file_path in file_list:
            fullname = class_path + file_path # 路徑+檔名
            print("當前處理的檔案是: ",fullname)  # 語料/train/pos/pos.txt
                            #  語料/train/neg/neg1.txt

            content = readfile(fullname).strip()  # 讀取檔案內容
            content = content.replace("\n", "").strip()  # 刪除換行和多餘的空格
            content_seg = jieba.cut(content)    # jieba分詞
            print("jieba分詞後:",content_seg)
            listcontent = ''
            for i in content_seg:
                listcontent += i
                listcontent += " "
                # listcontent.replace(' ','\n').replace('  ','\n')
            print(listcontent[0:10])
            listcontent = movestopwords(listcontent)    # 去除停用詞
            print("去除停用詞後:", listcontent[0:10])
            listcontent = listcontent.replace("   ", "\n").replace("  ", "\n")
            savefile(seg_dir + file_path, "".join(listcontent)) # 儲存