本文通过对中文维基百科数据的处理用来训练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