分词,筛选topn字词,并建立词向量记算相似度的记录:
#数据加载阶段
import xlrd
book = xlrd.open_workbook('object.xlsx') #读入 xlsx
sheet = book.sheet_by_index(0) #读入单页表
cols = sheet.ncols #读入列数
intents = [sheet.col_values(i) for i in range(sheet.ncols)] #读入所有列的内容
# 加载停用词
with open(r'hit_stopwords.txt','r',encoding = 'utf-8') as f:
stop_words = f.readlines() #加载哈工大的停用词表。可以在 https://github.com/goto456/stopwords 处下载到
stop_words = [re.sub(' |\n', '', i) for i in stop_words]
with open(r'extra_stopwords.txt','r',encoding = 'utf-8') as f:
stop_words_ = f.readlines() #加载自定义的停用词表,一般是在处理过程中手动加入的筛选值
stop_words_ = [re.sub(' |\n', '', i) for i in stop_words_]
stop_words.extend(stop_words_)
# 仅滤过非中文字符的函数段,用于找出分词得到的英文词们
def find_unchinese(m_str):
pattern = re.compile(r'[\u4e00-\u9fa5]')
unchinese = re.sub(pattern,"",m_str)
return unchinese
# 读入内容并进行分词
split_word = [] #存储中文分词结果的 list
split_word_english = [] #存储英文分词结果的 list
for intent in intents:
intent = [re.sub('\u3000| |\n','',str(i)) for i in intent] #滤掉空格及换行符
# text_cut = [jieba.lcut(str(i)) for i in intent] #默认分词方式,不重叠
# text_cut = [jieba.cut(str(i), cut_all=True) for i in intent] #全分词方式,结果最多,但内容有重叠之处
text_cut = [jieba.cut_for_search(str(i)) for i in intent] #搜索引擎分词方式,部分重叠,数量适中,所以选择这个方式
text_ = [[i.lower() for i in word if i.lower() not in stop_words] for word in text_cut] #再筛一遍非中文的关键字词
only_english = []
for line in text_:
only_english.append(find_unchinese(i) for i in line)
split_word.append(text_)
split_word_english.append(only_english)
# 通过 Counter 统计字频,方便筛选出 topn 字词
from collections import Counter
english_c = Counter()
for words in split_word_english[4]:
for word in words:
if len(word)>1 and word!= '\r\n':
english_c[word.lower()] += 1
#非中文分词结果中的 list
tech_top10 = [] #存储 topn 的 list
for (k,v) in english_c.most_common(10): #这里的数字就是 topn 中的 n
print("%s:%d"%(k,v))
tech_top10.append(k) #往存储 topn 的 list 里填值
english_c = sorted(english_c.items(),key= lambda item:item[1],reverse=True) #根据词频可对其进行排序,方便建立个人停用词表
#建立词向量,计算相关度并输出格式排列的计算表值代码
from gensim.models import Word2Vec
my_wv = Word2Vec(total_split_word, min_count=2, window=2, iter=50) #这里的 total_split_word 是要分析的文字段落分词得到的结果,是建立词向量的核心部段
with open('similar_ratio.txt','w',encoding='utf-8') as f: # 将结果输出到 similar_ratio.txt 这一文件中
f.write(' ')
for t in tech_top10: # 这里就是上面分出的 topn 的 list
f.write('\t{}'.format(t))
f.write('\n')
for s in simple_top30: # 遍历两个 topn 的 list 进行一一对应的相似度计算
f.write('{}'.format(s))
for t in tech_top10:
try: #计算相似度的过程可能会报错,需要有异常检测机制保底
f.write('\t{}'.format(my_wv.similarity(s,t))) #建立完之后可以通过词向量表来计算几个字词间的相似度
except:
f.write('\tcan not calculate!')
f.write('\n')
通过这个方式就可以简单计算出语料中的 topn 高频词,和他们之间的相关度了。
语料喂得越多就越接近真实场景,但也可以仅对所需要的部分文字段进行分析。
P.s. 建立出的词向量还有更多围绕相似度进行的操作,这里便不展开,记录下一些常用的操作。
更多的可以通过搜索 “”gensim Word2Vec“” 得到,这里不再细说。
gensim 是谷歌开源的一个简易且功能足够强大的词向量库,其官方网站为: https://code.google.com/p/word2vec/
# 计算两个词的相似度/相关程度
y1 = model.similarity(u"不错", u"好")
print u"【不错】和【好】的相似度为:", y1
print "--------\n"
# 计算某个词的相关词列表
y2 = model.most_similar(u"书", topn=20) # 20个最相关的
print u"和【书】最相关的词有:\n"
for item in y2:
print item[0], item[1]
print "--------\n"
# 寻找对应关系
print u"书-不错,质量-"
y3 = model.most_similar([u'质量', u'不错'], [u'书'], topn=3)
for item in y3:
print item[0], item[1]
print "--------\n"
# 寻找不合群的词
y4 = model.doesnt_match(u"书 书籍 教材 很".split())
print u"不合群的词:", y4
print "--------\n"