本文通過對中文維基百科數據的處理用來訓練word2vec模型,更深入的瞭解詞向量模型的訓練過程,並且對文本的處理進行掌握
python代碼如下所示(添加詳細註釋):
# -*-coding: UTF-8 -*-
# @Time:2019/8/28 19:02
# @author superxjz
# @func
import logging, jieba, os, re
from gensim.models import word2vec
#得到停用詞
def get_stopwords():
#這是關於日誌的設置函數
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO)
# 加載停用詞表
# set()函數創建一個無序不重複元素集,可進行關係測試,刪除重複數據,還可以計算交集、差集、並集等/類似是一個集合
stopword_set = set()
with open("../stop_words/stopwords.txt", 'r', encoding="utf-8") as stopwords:
for stopword in stopwords:
stopword_set.add(stopword.strip("\n"))
return stopword_set
'''
使用正則表達式解析文本
'''
#對維基數據進行處理的函數
def parse_zhwiki(read_file_path, save_file_path):
# 過濾掉<doc>
# 正則表達式
regex_str = "[^<doc.*>$]|[^</doc>$]"
#打開文件
file = open(read_file_path, "r", encoding="utf-8")
# 打開寫入文件
output = open(save_file_path, "w+", encoding="utf-8")
#將文件內的第一行數據(文章)寫入到content_line
content_line = file.readline()
# 獲取停用詞表
stopwords = get_stopwords()
# 定義一個字符串變量,表示一篇文章的分詞結果
article_contents = ""
#當文件內的數據沒有讀完的時候
while content_line:
#使用正則表達式進行匹配將句子匹配了出來
match_obj = re.match(regex_str, content_line)
#去除換行
content_line = content_line.strip("\n")
if len(content_line) > 0:
#如果match_obj爲真
if match_obj:
# 使用jieba對content_line進行分詞
words = jieba.cut(content_line, cut_all=False)
for word in words:
if word not in stopwords:
#將單詞寫入到article_contents
article_contents += word + " "
else:
if len(article_contents) > 0:
output.write(article_contents + "\n")
#將這一行重新又設置成了空的字符串
article_contents = ""
# 讀入第二行
content_line = file.readline()
# 關閉文件
output.close()
'''
將維基百科語料庫進行分類
'''
#對raw_corpus進行處理
def generate_corpus():
#原始的語料
zhwiki_path = "D:/dataset/NLP/zhwiki/AA"
#保存處理後的語料
save_path = "D:/dataset/NLP/zhwiki/AA"
#文件夾下不止一個文件
for i in range(3):
# os.path.join()函數:連接兩個或更多的路徑名組件
file_path = os.path.join(zhwiki_path, str("zh_wiki_0%s_jt" % str(i)))
#經過 parse_zhwiki這個函數已經將原始語料進行了處理,並且保存在了文件夾中
parse_zhwiki(file_path, os.path.join(save_path, "wiki_corpus0%s" % str(i)))
'''
合併分詞後的文件
'''
def merge_corpus():
# 打開處理後的維基文件夾
output = open("D:/dataset/NLP/zhwiki/AA/wiki_corpus","w",encoding="utf-8")
input = "D:/dataset/NLP/zhwiki/AA"
for i in range(3):
# 將input文件下的文件保存在output-一個文件下
file_path = os.path.join(input,str("wiki_corpus0%s"%str(i)))
file = open(file_path,"r",encoding="utf-8")
line = file.readline()
while line:
output.writelines(line)
line = file.readline()
file.close()
output.close()
if __name__ == "__main__":
#已經處理好的維基語料
input_file = "D:/dataset/NLP/zhwiki/AA/wiki_corpus"
file = open(input_file,"r",encoding="utf-8")
line = file.readline()
num = 1
while line:
print(line)
line = file.readline()
num += 1
if num > 10:
break
#利用處理好的中文維基語料進行訓練詞向量模型並且保存
sentences = word2vec.LineSentence("D:/dataset/NLP/zhwiki/AA/wiki_corpus")
model = word2vec.Word2Vec(sentences, size=250)
# 保存模型
model.save("model/wiki_corpus.model")
github源碼地址如下:https://github.com/steelOneself/NLP_learn/tree/master/zhwiki_chinese