cygwin下用Python比较两个文本的相似性,使用到了结巴分词以及余弦定理。
关于结巴分词,大家可以看看这篇文章《cygwin下用Python+jieba给文本分词并提取高频词》
- #!/usr/bin/env python
- # -*- coding: utf-8 -*
- import re
- from math import sqrt
- #You have to install the python lib
- import jieba
- def file_reader(filename,filename2):
- file_words = {}
- ignore_list = [u'的',u'了',u'和',u'呢',u'啊',u'哦',u'恩',u'嗯',u'吧'];
- accepted_chars = re.compile(ur"[\\u4E00-\\u9FA5]+")
- file_object = open(filename)
- try:
- all_the_text = file_object.read()
- seg_list = jieba.cut(all_the_text, cut_all=True)
- #print "/ ".join(seg_list)
- for s in seg_list:
- if accepted_chars.match(s) and s not in ignore_list:
- if s not in file_words.keys():
- file_words[s] = [1,0]
- else:
- file_words[s][0] += 1
- finally:
- file_object.close()
- file_object2 = open(filename2)
- try:
- all_the_text = file_object2.read()
- seg_list = jieba.cut(all_the_text, cut_all=True)
- for s in seg_list:
- if accepted_chars.match(s) and s not in ignore_list:
- if s not in file_words.keys():
- file_words[s] = [0,1]
- else:
- file_words[s][1] += 1
- finally:
- file_object2.close()
- sum_2 = 0
- sum_file1 = 0
- sum_file2 = 0
- for word in file_words.values():
- sum_2 += word[0]*word[1]
- sum_file1 += word[0]**2
- sum_file2 += word[1]**2
- rate = sum_2/(sqrt(sum_file1*sum_file2))
- print 'rate: '
- print rate
- file_reader('thefile.txt','thefile2.txt')
- #该片段来自于http://outofmemory.cn
我们先试一下,a1.txt和a2.txt为同一个文件时结果是什么?
这回rate值为0,说明两篇文章主题相似度非常低。
再找一篇原创文章和一篇伪原创文章来对比一下:
rate值为0.96,说明这两篇文章相似度非常高!可以像百度这样专业的搜索引擎,想要判断一篇文章是否是伪原创的,是多么容易.......
参考资料
1、《数学之美系列十二:余弦定理和新闻的分类》
2、《【百度搜索研发部】搜索背后的奥秘--浅谈语义主题计算》
转载请注明:思享SEO博客 » cygwin下用Python比较两个文本的相似性
扩展阅读
python3报错’encoding’ is an invalid keyword argument for this function
今天碰到一个奇怪的问题,在读txt的时候,报错'encoding' is an invalid keyword argument for this function。于是网上找了一下,这是版本的问题,如果是python2.7版本就会报错。可问题是我用......
什么是ZWNBSP,怎么去除零宽度空白字符
之前转载了一篇获取百度下拉的文章《Python获取百度下拉关键词》今天在使用过程中,发现可以访问接口获取下拉词,但是使用requests请求获取的的却是{}。我再将字符直接写入接口,而非用形参又没有问题。最后无奈将请求的url变量打印,输出的地址也没......
python获取当前上网IP地址的几种方法
在python使用场景中,有时候需要获取当前网络IP来实现一些功能。那么,如何用python来实现这个功能呢?下面,来讲讲我是怎么实现的。 通过访问IP网站获取 之前我一直用的获取的IP网站是 http://httpbin.org/ip 但是,今晚发......