分詞、去停用詞
#https://github.com/xgli/jieba
import os
import jieba
# 未分詞語料庫路徑
corpus_path =r' '
# 分詞後語料庫路徑
seg_path = r' '
# 停用詞路徑
stop_list_Path = r' '
def stopwordsList(stop_list_Path):
f = open(stop_list_Path,'r',encoding='utf-8')
stopwords = [line.strip() for line in f.readlines()]
return stopwords
def readfile(filepath):
f = open(filepath,'r',encoding='gb2312',errors='ignore')
content = f.read()
# read()返回的是字符串,讀全文本的內容。readline()返回一行,是字符串類型。readlines()讀取所有行,保存在列表中
f.close()
return content
# 這裏返回整個文本,以便後續進行分詞
def savefile(seg_path,content):
f = open(seg_path,'w',encoding='utf-8')
f.write(content)
f.close()
def tikenizer_and_removeStoplist(corpus_path,stop_list_Path):
cate_dir = os.listdir(corpus_path) # 獲取子類別目錄
for cate in cate_dir:
cate_complete_dir = corpus_path+'\\'+cate+"\\" # 獲取子類別的完整路徑
seg_cate_complete_dir = seg_path + '\\' + cate + "\\"
if not os.path.exists(seg_cate_complete_dir): # 創建分詞後的保存的路徑
os.makedirs(seg_cate_complete_dir)
file_dir = os.listdir(cate_complete_dir)#獲取每個類別下的文件
for file in file_dir:
file_complete_dir = cate_complete_dir+file # 獲取每個類別下的文件的完整路徑
content = readfile(file_complete_dir) # 返回這個文本
# 對文本進行處理,刪除換行以及多餘空格
content = content.replace("\n",'').strip()
content_seg = jieba.cut(content)
#創建停用詞表
stopwords = stopwordsList(stop_list_Path)
outstr =''
for word in content_seg:
if word not in stopwords:
if word !='\t':
outstr+=word
outstr+=" "
savefile(seg_cate_complete_dir+"\\"+file,' '.join(outstr))
print("分詞結束")