利用中文维基百科训练词向量模型

8 篇文章 0 订阅

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值