参考:python文本相似度计算
原始语料格式:一个文件,一篇文章。
#
!/usr/bin/env python
#
-*- coding: UTF-8 -*-
import
jieba
from
gensim
import
corpora,models,similarities
import
codecs
def
cut_words(file):
with open(file,
'
r
'
,encoding=
"
utf-8
"
) as f:
text
=
f.read()
words
=
jieba.lcut(text)
#
print(len(words),words) #查看分词结果
return
words
def
drop_Disable_Words(cut_res,stopwords):
res
=
[]
for
word
in
cut_res:
if
word
in
stopwords
or
word ==
"
\n
"
or
word ==
"
\u3000
"
:
continue
res.append(word)
#
print(len(res),res) #查看去停用词结果
return
res
def
read_stop_word(file_path):
file
=
file_path
stopwords
= codecs.open(file,
'
r
'
,encoding=
'
utf8
'
).readlines()
stopwords
= [ w.strip()
for
w
in
stopwords ]
return
stopwords
#
读取原始语料、停用词表
files = [
'
file1.txt
'
,
'
file2.txt
'
,
'
file3.txt
'
]
stopwords
= read_stop_word(
"
stop_word.txt
"
)
#
分词、去停用词
corpus =
[]
for
file
in
files:
#
分词
cut_res =
cut_words(file)
#
去停用词
res =
drop_Disable_Words(cut_res,stopwords)
corpus.append(res)
#
print(len(corpus))
#
建立词袋模型
dictionary =
corpora.Dictionary(corpus)
doc_vectors
= [dictionary.doc2bow(text)
for
text
in
corpus]
#
print(len(doc_vectors),doc_vectors)
#
####################################################################
#
print("文档数目:")
#
print (dictionary.num_docs)
#
#
print("所有词的个数:")
#
print(dictionary.num_pos )
#
#
print("单词在文档中出现的次数:")
#
print(dictionary.dfs )
#
#
print("字典,{单词id:对应的词}")
#
print((dictionary.id2token))
#
#
print ("字典,{词:对应的单词id}")
#
print((dictionary.token2id))
#
print ("每个文件中不重复词个数的和")
#
print(dictionary.num_nnz) #每个文件中不重复词个数的和
#
#########################################################################
tfidf
=
models.TfidfModel(doc_vectors)
tfidf_vectors
=
tfidf[doc_vectors]
print
(len(tfidf_vectors))
print
(len(tfidf_vectors[0]))
print
(tfidf_vectors[0])
#
建立TF-IDF模型
def
TF_IDF(tfidf_vectors,doc_vectors):
index
=
similarities.MatrixSimilarity(tfidf_vectors)
sims
=
index[doc_vectors[0]]
print
(list(enumerate(sims)))
#
建立LSI模型
def
LSI(tfidf_vectors,dictionary,doc_vectors,theme_num):
lsi
= models.LsiModel(tfidf_vectors, id2word=dictionary, num_topics=
theme_num)
lsi_vector
=
lsi[tfidf_vectors]
query_lsi
=
lsi[doc_vectors[0]]
index
=
similarities.MatrixSimilarity(lsi_vector)
sims
=
index[query_lsi]
print
(list(enumerate(sims)))
#
使用LSI模型计算相似度
LSI(tfidf_vectors,dictionary,doc_vectors,2
)
#
使用TF-IDF模型计算相似度
TF_IDF(tfidf_vectors,doc_vectors)
原始语料格式如下示例:
汽车 酷似卡宴 华泰新SUV宝利格广州车展上市 http://auto.data.people.com.cn/news/story_428419.html 华泰在推出自主轿车B11后,又一款自主SUV宝利格已经确定将在11月下旬的广州车展上市正式上市,新车将与B11一样搭载1.8T汽油机和2.0T柴油机,预计售价10-15万元之间,最大的亮点就是酷似保时捷卡宴的外观。;泰宝利格凭借酷似保时捷卡宴的外观而颇受关注,这款车整体外形设计厚重敦实,有着SUV应有的硬朗和雄浑,其车身采用了大量的镀铬装饰和银色装饰件,凸显年轻和时尚;同时宝利格也继承了华泰家族式脸谱造型,与华泰B11相似的前脸采用了倒梯形网状前格栅,新款双氙气大灯不仅提供更加理想的照明效果,也将成为宝利格的独特标识。;泰宝利格2620毫米的轴距带来的车内空间宽大而理想,其内饰方面也与卡宴经典车型非常接近,内饰配色采用米色和浅棕色的组合,并配备木纹饰板以提升质感,有着典型的欧系风情,带给消费者极佳的视觉享受。此外,B35还配备了大屏幕的液晶屏和自动空调等多种舒适性配置。T诙力上,华泰宝利格使用的是源于意大利VM技术的清洁柴油发动机,搭载1.8T涡轮增压发动机,最大功率160马力,最大扭矩215Nbm,采用全时四轮技术驱动。这一动力配置再次彰显华泰汽车低碳、环保的产品理念,迎合了高端人士对环保低碳的需求。;泰宝利格采用的是前麦弗逊、后多连杆的前后独立悬挂设置,车身也是更强调舒适性能的承载式车身,定位上将更加偏向都市SUV。就定位而言,未来宝利格将作为华泰SUV系列中的高端产品,与圣达菲一样主攻城市SUV领域。...全文 > (来源:网上车市)
汽车 最受欢迎TOP10车型出炉 帝豪EC7脱颖而出 http://auto.data.people.com.cn/news/story_390275.html 爱美之心人皆有之,汽车的外观炫感度所形成的冲击力,往往会给第一眼与之接触的消费者留下挥之不去的深刻印象。当前,随着中国汽车市场发展的日趋成熟,消费者对汽车外型的要求也变得越来越挑剔和苛刻,经媒体广泛调查发现,"车型外观"已经成为购车者的首选考虑因素之一。D敲矗究竟哪些品牌的车型外观更酷、更赞、更大气,同时也更加受到大众 的认同和青睐呢?为了解答这个疑问,汽车点评网联合《汽车杂志》、《轰》杂志以及互联网消费者调研中心在近期举办了"全球最受欢迎外观车型大评选"活动。F车也选美,帝豪EC7脱颖而出5酆溃牛茫钒潦友窍党迪盗校一举从众多参选车型中脱颖而出,成为全球十大最受欢迎外观车型之一,可以说是丝毫不使人感到意外的。我们可以看到,帝豪EC7外观的优越性、高端性塑造,凸显出其强劲的全球竞争实力和同欧美系品牌分庭抗衡的信心。M时,帝豪EC7的此番登顶,也意味着国产汽车品牌将迎来一个全新的历程,并且对国产汽车进入快速崛起模式同样具有深刻的启示意义。正如评选参与者所言:"帝豪EC7车型外观大气、稳重,是近年来国产车中外观设计最好的车型之一。找到了价格、安全、空间、动力、材质、做工的平衡点,是一款性价比很高的车型。"9产车发力,帝豪系列众望所归O笳髯牛⒑阑、稳健、力量"的帝豪EMGRAND系列可谓国产汽车中的精品,此系列中的各款车型皆具大家风范,圆润、饱满的构造,以及简洁、明快的线条,使整个车型外观尽显大气并活力四射。4拥酆溃牛茫返剑牛茫福诠释了吉利帝豪 向欧洲标准看齐的步伐正不断加快,而由国外著名设计公司组成的团队,也给帝豪的工艺水平提升带来了质的飞跃。之所以帝豪总能给人一种国际尖端品牌的驾乘感受,与这些因素是分不开的。L氐愕娜诤稀⑿阅艿谋Vぁ⒆鸸蟮奶逖椤⒑侠淼男约郏这些都是帝豪能在此次评选活动中笑傲群雄的基础,同时也证明了帝豪不断跻身国际中高端汽车行业的实力,吉利帝豪做为国产车成功的典范,不久的将来,将在世界汽车市场上享有自己的一席之地。#保最受欢迎TOP10车型出炉 帝豪EC7脱颖而出
#
!/usr/bin/env python
#
-*- coding: UTF-8 -*-
import
pandas as pd
import
jieba
def
drop_stopwords(content_res,stopwords):
contents_clean
=
[]
all_words
=
[]
for
line
in
content_res:
#
用于存储清洗后的词
line_clean =
[]
for
word
in
line:
#
如果这个词出现在停用词里,过滤掉
if
word
in
stopwords:
continue
#
存储过滤后的词
line_clean.append(word)
all_words.append(str(word))
#
把已经清洗的列表存储起来
contents_clean.append(line_clean)
return
contents_clean,all_words
#
contents_clean为清理完的数据,为二维列表
#
读取语料数据
df_news = pd.read_table(
"
val.txt
"
,names=[
'
category
'
,
'
theme
'
,
'
url
'
,
'
content
'
],encoding=
'
utf-8
'
)
df_news
=
df_news.dropna()
#
将数据转为二维列表:list of list
content = df_news.content.values.tolist()
#
将每个content列转为列表,结果为二维列表
#
读取停用词表
df_stop= pd.read_csv(
"
stop_word.txt
"
,encoding=
"
utf-8
"
,sep =
"
\n
"
,names = [
'
stopword
'
])
#
将数据转为二维列表:list of list
stopwords =
df_stop.stopword.values.tolist()
#
分词,数据格式:list of list
content_res =
[]
for
line
in
content:
current_segment
=
jieba.lcut(line)
if
len(current_segment) > 1
and
current_segment !=
'
\r\n
'
:
content_res.append(current_segment)
#
清停用词,数据格式:list of list
contents_clean, all_words =
drop_stopwords(content_res,stopwords)
#
查看清洗后的数据
#
df_content =pd.DataFrame({'content_res':contents_clean})
#
print(df_content.head())
#
词频统计
#
df_all_words = pd.DataFrame({'all_words':all_words})
#
words_count = df_all_words.groupby(by=['all_words'])['all_words'].agg({"count":np.size})
#
words_count =words_count.reset_index().sort_values(by=['count'],ascending=False)
#
print(words_count.head())

