本文已参与「新人创作礼」活动,一起开启掘金创作之路。
前言
中文语料库一般都是极为稀少的,要进行中文词向量的训练可能是极为困难的,这时候我们需要使用中文维基百科来进行词向量的训练。
一、前提知识
1-1、中文维基百科的下载
wiki语料库下载网址:dumps.wikimedia.org/. 最近的中文wiki语料:dumps.wikimedia.org/zhwiki/late…. 我们选择其中的一个内容比较丰富的文件:zhwiki-latest-pages-articles.xml.bz2
1-2、抽取正文内容,繁体转换为简体
1-2-1、抽取正文内容
1-2-2、繁体转换为简体
opencc库:繁体转化为简体非常好用的一个库。 下载:pip install opencc-python-reimplemented==0.1.4 python2和python3使用opencc库的区别:
# python2使用
import opencc
opencc.convert()
# python3使用
from opencc import OpenCC
# 下载的包里面会有s2t.json文件,代表简体转繁体,t2s代表繁体到简体。
cc = OpenCC('s2t')
cc.convert()
1-3、特征工程
def wiki_replace(d):
s = d[1]
s = re.sub(':*{\|[\s\S]*?\|}', '', s)
s = re.sub('<gallery>[\s\S]*?</gallery>', '', s)
s = re.sub('(.){{([^{}\n]*?\|[^{}\n]*?)}}', '\\1[[\\2]]', s)
s = filter_wiki(s)
s = re.sub('\* *\n|\'{2,}', '', s)
s = re.sub('\n+', '\n', s)
s = re.sub('\n[:;]|\n +', '\n', s)
s = re.sub('\n==', '\n\n==', s)
s = u'【' + d[0] + u'】\n' + s
return cc.convert(s).strip()
1-4、训练词向量
将前面得到的中文语料库使用jieba分词工具进行分词之后,使用word2vec工具进行训练。
二、实战训练
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# 使用python2来写。
# import sys
# reload(sys)
# sys.setdefaultencoding('utf8')
# 以下代码是基于python3.8来进行的
import imp
import sys
imp.reload(sys)
from gensim.corpora.wikicorpus import extract_pages, filter_wiki
import bz2file
import re
# 2.7使用的包
# import opencc
# 3.8使用的包
from opencc import OpenCC
from tqdm import tqdm
import codecs
wiki = extract_pages(bz2file.open('./zhwiki-latest-pages-articles.xml.bz2'))
cc = OpenCC('t2s')
def wiki_replace(d):
s = d[1]
s = re.sub(':*{\|[\s\S]*?\|}', '', s)
s = re.sub('<gallery>[\s\S]*?</gallery>', '', s)
s = re.sub('(.){{([^{}\n]*?\|[^{}\n]*?)}}', '\\1[[\\2]]', s)
s = filter_wiki(s)
s = re.sub('\* *\n|\'{2,}', '', s)
s = re.sub('\n+', '\n', s)
s = re.sub('\n[:;]|\n +', '\n', s)
s = re.sub('\n==', '\n\n==', s)
s = u'【' + d[0] + u'】\n' + s
return cc.convert(s).strip()
i = 0
f = codecs.open('wiki.txt', 'w', encoding='utf-8')
w = tqdm(wiki, desc=u'已获取0篇文章')
for d in w:
if not re.findall('^[a-zA-Z]+:', d[0]) and d[0] and not re.findall(u'^#', d[1]):
s = wiki_replace(d)
f.write(s + '\n\n\n')
i += 1
if i % 100 == 0:
w.set_description(u'已获取%s篇文章' % i)
f.close()