搜狗语料库word2vec获取词向量

2023-05-16

一、中文语料库

本文采用的是搜狗实验室的搜狗新闻语料库,数据链接 http://www.sogou.com/labs/resource/cs.php

首先对搜狗语料库的样例文件进行分析。搜狗语料库由搜狗实验室提供,我们使用搜狗新闻语料库,下载地址在:http://www.sogou.com/labs/resource/cs.php。分析语料格式时先下载迷你版分析。 

下载下来的文件名为: news_sohusite_xml.smarty.tar.gz

二、数据预处理

2.1 解压并查看原始数据

cd 到原始文件目录下,执行解压命令:

tar -zvxf news_sohusite_xml.smarty.tar.gz

得到文件 news_sohusite_xml.dat, 用vim打开该文件,

vim news_sohusite_xml.smarty.dat

 得到如下结果:

2.2 取出内容

取出<content>  </content> 中的内容,执行如下命令:

cat news_sohusite_xml.smarty.dat | iconv -f gbk -t utf-8 -c | grep "<content>"  > corpus.txt 

 windows下可以使用

type news_sohusite_xml.smarty.dat | iconv -f gbk -t utf-8 -c | findstr "<content>"  > corpus.txt 

得到文件名为corpus.txt的文件,可以通过vim 打开

vim corpus.txt

得到如下效果:

 

 

2.3 分词

注意,送给word2vec的文件是需要分词的,分词可以采用jieba分词实现,安装jieba 分词 

##!/usr/bin/env python
## coding=utf-8
import jieba

filePath='corpus.txt'
fileSegWordDonePath ='corpusSegDone.txt'
# read the file by line
fileTrainRead = []
#fileTestRead = []
with open(filePath,encoding='utf-8') as fileTrainRaw:
    for line in fileTrainRaw:
        fileTrainRead.append(line)

# define this function to print a list with Chinese
def PrintListChinese(list):
    for i in range(len(list)):
        print(list[i])
# segment word with jieba
fileTrainSeg=[]
for i in range(len(fileTrainRead)):
    fileTrainSeg.append([' '.join(list(jieba.cut(fileTrainRead[i][9:-11],cut_all=False)))])
    if i % 100 == 0 :
        print(i)
# to test the segment result
#PrintListChinese(fileTrainSeg[10])
# save the result
with open(fileSegWordDonePath,'wb') as fW:
    for i in range(len(fileTrainSeg)):
        fW.write(fileTrainSeg[i][0].encode('utf-8'))
        fW.write('\n'.encode("utf-8"))

可以得到文件名为 corpusSegDone.txt 的文件,需要注意的是,对于读入文件的每一行,使用结巴分词的时候并不是从0到结尾的全部都进行分词,而是对[9:-11]分词 (如行22中所示: fileTrainRead[i][9:-11] ),这样可以去掉每行(一篇新闻稿)起始的<content> 和结尾的</content>。

得到如下图所示的结果:

三、构建词向量

3.1word2vec训练词向量

word2vec模型的原理这里不再讲解,网上随便一搜,可以找到很多教程,这里是给个实例,基于上面处理好的语料训练词向量,使用的工具是gensim中自带的word2vec模型。

import logging
import gensim.models as word2vec
from gensim.models.word2vec import LineSentence

def train_word2vec(dataset_path, model_path, size=100, window=5, binary=True):
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    # 把语料变成句子集合
    sentences = LineSentence(dataset_path)
    # 训练word2vec模型
    model = word2vec.Word2Vec(sentences, size=size, window=window, min_count=5, workers=4, iter=10)
    # 保存word2vec模型
    if binary:
        model.wv.save_word2vec_format(model_path, binary=True)
    else:
        model.wv.save_word2vec_format(model_path, binary=False)

def load_word2vec_model(w2v_path):
    # load word2vec
    model = word2vec.KeyedVectors.load_word2vec_format(w2v_path, binary=True)
    return model

def calculate_most_similar(model, word):
    similar_words = model.most_similar(word)
    print(word)
    for term in similar_words:
        print(term[0], term[1])
        
dataset_path = "corpusSegDone.txt"
save_model_path = "corpusWord2Vec.bin" # save_binary=True
#save_model_path = "word2vec_model.txt" # save_binary=False

train_word2vec(dataset_path, save_model_path, size=100, window=5, binary=True)

model = load_word2vec_model('corpusWord2Vec.bin')
print (model.vectors)

3.2 显示并使用词向量

 查看词向量

model = load_word2vec_model('corpusWord2Vec.bin')
print (model.vectors)

可以得到如下结果:

 

3.3将词向量bin格式转化为txt格式

##将词向量模型生成的bin转化为txt格式
import codecs 
import gensim 
def bin2txt(path_to_model, output_file):  
    output = codecs.open(output_file, 'w' , 'utf-8')  
    model = gensim.models.KeyedVectors.load_word2vec_format(path_to_model, binary=True)  
    print('Done loading Word2Vec!')  
    vocab = model.vocab  
    for item in vocab:  
        vector = list()  
        for dimension in model[item]:  
            vector.append(str(dimension))  
        vector_str = ",".join(vector)  
        line = item + "\t"  + vector_str   
        output.writelines(line + "\n")  #本来用的是write()方法,但是结果出来换行效果不对。改成writelines()方法后还没试过。
    output.close()  
    

output_file = 'corpusWord2Vec.txt'  
bin2txt(save_model_path, output_file)  

结果显示:

完整代码如下

##!/usr/bin/env python
## coding=utf-8

#####jieba分词
import jieba

filePath='corpus.txt'
fileSegWordDonePath ='corpusSegDone.txt'
# read the file by line
fileTrainRead = []
#fileTestRead = []
with open(filePath,encoding='utf-8') as fileTrainRaw:
    for line in fileTrainRaw:
        fileTrainRead.append(line)

# define this function to print a list with Chinese
def PrintListChinese(list):
    for i in range(len(list)):
        print(list[i])
# segment word with jieba
fileTrainSeg=[]
for i in range(len(fileTrainRead)):
    fileTrainSeg.append([' '.join(list(jieba.cut(fileTrainRead[i][9:-11],cut_all=False)))])
    if i % 100 == 0 :
        print(i)
# to test the segment result
#PrintListChinese(fileTrainSeg[10])
# save the result
with open(fileSegWordDonePath,'wb') as fW:
    for i in range(len(fileTrainSeg)):
        fW.write(fileTrainSeg[i][0].encode('utf-8'))
        fW.write('\n'.encode("utf-8"))

###训练词向量
import logging
import gensim.models as word2vec
from gensim.models.word2vec import LineSentence

def train_word2vec(dataset_path, model_path, size=100, window=5, binary=True):
    logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
    # 把语料变成句子集合
    sentences = LineSentence(dataset_path)
    # 训练word2vec模型
    model = word2vec.Word2Vec(sentences, size=size, window=window, min_count=5, workers=4, iter=10)
    # 保存word2vec模型
    if binary:
        model.wv.save_word2vec_format(model_path, binary=True)
    else:
        model.wv.save_word2vec_format(model_path, binary=False)

def load_word2vec_model(w2v_path):
    # load word2vec
    model = word2vec.KeyedVectors.load_word2vec_format(w2v_path, binary=True)
    return model

def calculate_most_similar(model, word):
    similar_words = model.most_similar(word)
    print(word)
    for term in similar_words:
        print(term[0], term[1])
        
dataset_path = "corpusSegDone.txt"
save_model_path = "corpusWord2Vec.bin" # save_binary=True
#save_model_path = "word2vec_model.txt" # save_binary=False

#train_word2vec(dataset_path, save_model_path, size=100, window=5, binary=True)
model = load_word2vec_model('corpusWord2Vec.bin')
print (model.vectors)

##将词向量模型生成的bin转化为txt格式
import codecs 
import gensim 
def bin2txt(path_to_model, output_file):  
    output = codecs.open(output_file, 'w' , 'utf-8')  
    model = gensim.models.KeyedVectors.load_word2vec_format(path_to_model, binary=True)  
    print('Done loading Word2Vec!')  
    vocab = model.vocab  
    for item in vocab:  
        vector = list()  
        for dimension in model[item]:  
            vector.append(str(dimension))  
        vector_str = ",".join(vector)  
        line = item + "\t"  + vector_str   
        output.writelines(line + "\n")  #本来用的是write()方法,但是结果出来换行效果不对。改成writelines()方法后还没试过。
    output.close()  
    

output_file = 'corpusWord2Vec.txt'  
bin2txt(save_model_path, output_file)  
  

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

搜狗语料库word2vec获取词向量 的相关文章

随机推荐

  • web内外网判断界面

    因日常需要 xff0c 我们在实验室内网中部署了一个服务 xff0c 在校园网内都能正常访问 xff0c 同时配置了内网穿透服务 xff0c 实现外网也能正常访问 但外网访问毕竟是通过内网穿透实现 xff0c 稳定性与网速都有限制 xff0
  • 为无登陆鉴权功能的接口与网站添加登陆鉴权功能

    1 缘由 本人部分服务的测试接口为方便日常测试调试 xff0c 使用了 ip 43 端口 的形式进行访问 xff0c 并且未配置账号密码鉴权机制 在日常测试一段时间后 xff0c 终于还是收到了来自腾讯云的监管通知 xff0c 说服务存在数
  • RoboMaster机器人运行教程(一)

    1 环境配置 系统 xff1a ubuntu16 04 xff0c 安装ROS 2 基础学习 需要C 43 43 和python基础 xff0c 和ROS的基础知识 xff0c 网上有很多教程 xff0c 推荐知乎大佬教程 xff1a 我的
  • slambook2+ch7+pose_estimation_2d2d+估计多张图像之间的位姿

    算法 计算第一张图和第二张图的关键点并匹配以第一张图的相机坐标为世界坐标 xff0c 计算第二张图相对第一张图的旋转矩阵 平移矩阵不断更新第一张图 xff0c 在进行第二次计算时 xff0c 以第二张图为第一张图 xff0c 以第二张图的相
  • 重做Unbuntu 18.0.43 LTS系统 并为SLAM配置环境

    目录 前言 一 安装列表 1 Ubuntu 18 0 43 LTS 1 0 A 搜狗输入法 1 0 B ibus输入法安装 1 1 更换软件源 1 2 安装vim curl等工具 1 3 安装浏览器Chrome git等 1 4 安装g 4
  • PostMan各个版本下载

    打开地址 xff1a https gitee com hlmd PostmanCn
  • 快速解决matlab出现错误使用mex,未找到支持的编译器或 SDK的提示

    matlab mex命令提示找不到编译器或SDK 参考博客 xff1a https blog csdn net cfqcfqcfqcfqcfq article details 63295746 utm source 61 blogxgwz1
  • linux 串口应用层API

    include lt termios h gt struct termios oldtio newtio fd 61 open dev tty0 O RDWR O NOCTTY tcgetattr fd amp oldtio 获取终端参数
  • 2022年中国研究生数学建模竞赛B题-方形件组批优化问题

    一 背景介绍 智能制造被 中国制造2025 列为主攻方向 而个性化定制 更短的产品及系统生命周期 互联互通的服务模式等成为目前企业在智能制造转型中的主要竞争点 以离散行业中的产品为例 xff0c 如电子器件 汽车 航空航天零部件等 xff0
  • 无线网络知识、WiFi原理

    无线网络 B站链接 一 电磁波的传输 电磁波传播方式 地波 xff08 低于2MHZ xff09 天波 2MHZ 30MHZ 直线波 30MHZ以上 电磁波的发射与接收装置 天线 作用 xff1a 将电磁波辐射到空间中或收集电磁波 辐射模式
  • yolov5输出检测到的目标坐标信息

    找到detect py文件 span class token keyword for span span class token operator span xyxy span class token punctuation span co
  • TCP之 select模型

    前记 xff1a select模型主要用于解决tcp通信中 xff0c 每次处理一个独立的客户都要单独的开线程 xff0c 这样会导致客户连接数很大时 xff0c 线程数也会很多 而使用select就会将线程缩减至2个 xff0c 一个主线
  • ROS入门:GPS坐标转换&Rviz显示轨迹

    GPS信息是无法直接绘制轨迹的 xff0c 因为其x xff0c y为经纬度 xff0c z为高度 xff0c 单位不一样 xff0c 本程序实现了以下功能 xff1a 1 将GPS轨迹 xff0c 从经纬度WGS 84坐标转换到真实世界x
  • ubuntu实用技巧

    ubuntu 截图 xff03 保存到图片文件夹 Print Screen 截取整个桌面 Alt 43 Print Screen 截取选中的窗口 Shift 43 Print Screen 自由选区 xff03 复制到剪贴板 Ctrl 43
  • 在ThinkPad X280加装M.2硬盘上安装 Ubuntu 18.04.3 填坑记录

    填坑背景 用了一段时间的X280后 xff0c 突然想在M 2接口上加装一个 NVMe 2242 的SSD xff0c 发现 Lenovo 的BIOS设置的非常奇特 能够检测到这个硬盘 xff0c 但是启动项里就是不能识别 xff01 或许
  • sip注册示例

    这里给出一个sip注册的示例 xff0c 其中平台注册的密码为12345678 xff0c 供相关开发参考 REGISTER sip 34020000002000000001 64 192 168 88 119 SIP 2 0 Via SI
  • spring security验证流程

    工作需要 xff0c 又弄起了权限的管理 虽然很早以前都了解过基于容器的权限实现方式 xff0c 但是一直都觉得那东西太简陋了 后来使用liferay时发现它的权限系统的确做得很优秀 xff0c 感觉这也可能是它做得最出色的地方吧 但是当时
  • On make and cmake

    你或许听过好几种 Make 工具 xff0c 例如 GNU Make xff0c QT 的 qmake xff0c 微软的MS nmake xff0c BSD Make xff08 pmake xff09 xff0c Makepp xff0
  • 制作html css 步骤进度条(完整代码)

    这个动画步骤进度条的css制作的非常简单 那里有两个按钮可以控制步骤 xff0c 它们将逐步进行 我在这个多步骤进度条 css 中使用了 4 个步骤 如果你愿意 xff0c 你可以使用更多 我使用了一些 javascript 来创建这一步进
  • 搜狗语料库word2vec获取词向量

    一 中文语料库 本文采用的是搜狗实验室的搜狗新闻语料库 xff0c 数据链接 http www sogou com labs resource cs php 首先对搜狗语料库的样例文件进行分析 搜狗语料库由搜狗实验室提供 xff0c 我们使