自然语言处理实践——1.词向量word2vec的转化

1. 为什么要进行词向量的转化?

计算机看不懂我们人类的语言文字,必须转化成机器看得懂的形式才能进行下一步的处理。

2. 文字的预处理和词向量化

自然语言中有很多字符是无用的(如:“吗”,“的”,“。”,“,”),并且我们希望把整句整段的语言转成容易处理的形式。不过在编程之前我们需要对文件的目标进行良好的规划:
自然语言处理实践——1.词向量word2vec的转化_第1张图片
data_try文件中我们放了两个对违纪党员干部的通报文件:
在这里插入图片描述

然后代码如下,这里我们使用的是Pycharm中的jupyter notebook:

#%%

import pandas as pd
import os,pathlib
import re
import jieba
import logging
from gensim.models import word2vec

#%%

root = pathlib.Path(os.path.abspath('__file__')).parent.parent #当前文件的上两级目录
data_path =  os.path.join(root,"data","data_try.xlsx") #data文件夹中的data_try文件

df = pd.read_excel(data_path) #读取文件
df.columns = ['content']

#%%

# CELL: 预处理,包括去掉符号和停用词
stopwords_path = os.path.join(root,"data","hit_stopwords.txt") #哈工大停词表
semantic_train_path = os.path.join(root,"data","semantic_resource.txt") #训练语料的目录
jieba.load_userdict(stopwords_path)


def stopwordslist():
    stopwords = [line.strip() for line in open(stopwords_path,encoding='UTF-8').readlines()]
    return stopwords

def sentence_write(content,path):
    """

    :param content: 等待分词和去掉停用词的内容
    :param path: 储存的目录
    :return: 无返回值
    """
    content_spliting = jieba.lcut(content.strip())
    stopwords = stopwordslist()
    result = ""
    #在停词表中的词去掉
    for word in content_spliting:
        if word not in stopwords:
            if word != '\t':
                result += word
                result += " "
    f = open(path, mode="a", encoding="utf-8")
    f.write(result)
    f.close()
    return 0

def clean_sentence(line):
    """
    去掉无用的符号
    :param line:
    :return:
    """
    line = re.sub(
            "[\s+\-\|\!\/\[\]\{\}_,.$%^*(+\"\')]+|[::;+——()?【】《》“”!,。?、~@#¥%……&*()]+|", '',line) #对无意义字符串进行替换
    return line

def proc(df,attr):
    df[attr] = df[attr].apply(clean_sentence)
    return df

df = proc(df,'content')

for index,row in df.iterrows():
    sentence_write(row['content'],semantic_train_path)


#%%

#进行语料训练
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.INFO)

sentences = word2vec.Text8Corpus(semantic_train_path)
# 训练模型,部分参数如下
model = word2vec.Word2Vec(sentences, size=100, hs=1, min_count=1, window=3)

#%%

y = model.most_similar(u'阻挠', topn = 10)
y

总的来说,上面代码的作用是加载Excel文件中的数据,进行清洗和去掉停用词,从而得到一个由有效词语组成的txt文件,然后将这个文件丢到logging和word2vec的包中进行向量化处理。最后的most_similar的作用是训练后的词向量的相关性。
另外与one-hot词向量不同,word3vec的向量化可以体现词的相关性,具体的请参考我的其他博文。

你可能感兴趣的:(paper,机器学习,自然语言处理)