中文语料库一般都是极为稀少的,要进行中文词向量的训练可能是极为困难的,这时候我们需要使用中文维基百科来进行词向量的训练。
1-1、中文维基百科的下载
1-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('[\s\S]*?', '', 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('[\s\S]*?', '', 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()
回家之后,无所事事了几天,打游戏也觉得索然无味,嗯,还是敲代码比较有意思。
Original: https://blog.csdn.net/weixin_42475060/article/details/122711953
Author: ㄣ知冷煖★
Title: 维基百科的语料库下载以及信息提取笔记
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/544701/
转载文章受原作者版权保护。转载请注明原作者出处!