cygwin下用Python比较两个文本的相似性

Python与SEO 思享 2025浏览

cygwin下用Python比较两个文本的相似性,使用到了结巴分词以及余弦定理。

关于结巴分词,大家可以看看这篇文章《cygwin下用Python+jieba给文本分词并提取高频词》

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*
  3. import re
  4. from math import sqrt
  5. #You have to install the python lib
  6. import jieba
  7. def file_reader(filename,filename2):
  8.     file_words = {}
  9.     ignore_list = [u'的',u'了',u'和',u'呢',u'啊',u'哦',u'恩',u'嗯',u'吧'];
  10.     accepted_chars = re.compile(ur"[\\u4E00-\\u9FA5]+")
  11.     file_object = open(filename)
  12.     try:
  13.         all_the_text = file_object.read()
  14.         seg_list = jieba.cut(all_the_text, cut_all=True)
  15.         #print "/ ".join(seg_list)
  16.         for s in seg_list:
  17.             if accepted_chars.match(s) and s not in ignore_list:
  18.                 if s not in file_words.keys():
  19.                     file_words[s] = [1,0]
  20.                 else:
  21.                     file_words[s][0] += 1
  22.     finally:
  23.         file_object.close()
  24.     file_object2 = open(filename2)
  25.     try:
  26.         all_the_text = file_object2.read()
  27.         seg_list = jieba.cut(all_the_text, cut_all=True)
  28.         for s in seg_list:
  29.             if accepted_chars.match(s) and s not in ignore_list:
  30.                 if s not in file_words.keys():
  31.                     file_words[s] = [0,1]
  32.                 else:
  33.                     file_words[s][1] += 1
  34.     finally:
  35.         file_object2.close()
  36.     sum_2 = 0
  37.     sum_file1 = 0
  38.     sum_file2 = 0
  39.     for word in file_words.values():
  40.         sum_2 += word[0]*word[1]
  41.         sum_file1 += word[0]**2
  42.         sum_file2 += word[1]**2
  43.     rate = sum_2/(sqrt(sum_file1*sum_file2))
  44.     print 'rate: '
  45.     print rate
  46. file_reader('thefile.txt','thefile2.txt')
  47. #该片段来自于http://outofmemory.cn

我们先试一下,a1.txt和a2.txt为同一个文件时结果是什么?

结果

这回rate值为0,说明两篇文章主题相似度非常低。

再找一篇原创文章和一篇伪原创文章来对比一下:

不相关的内容

rate值为0.96,说明这两篇文章相似度非常高!可以像百度这样专业的搜索引擎,想要判断一篇文章是否是伪原创的,是多么容易.......

参考资料

1、《数学之美系列十二:余弦定理和新闻的分类
2、《【百度搜索研发部】搜索背后的奥秘--浅谈语义主题计算

推荐阅读

Python实现聚合问答采集文章

最近在一个社区得到了一个用python聚合问答的工具,但是因为已经打包成程序了,所以无法研究,于是在网上找了一个网友分享的源代码,转载于此,供志愿者学习和后期扩展。这个工具可以通过头条搜索、百度下拉结果、搜狗下拉、百度知道搜索、新浪爱问、搜狗问问,将......

pycharm怎么用国内镜像安装第三方库

1、在pycharm中打开Terminal,如下图。 2、以安装pymysql库为例,输入以下命令回车即可使用镜像安装。 pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pymysql ......

win10系统安装软件错误”The installer has encountered an unexpected error…error code is 2503″

在Windows10系统中,错误“安装程序在安装此软件包时遇到意外错误。这可能表明包装有问题。错误代码是2503。安装python3.8.9时报告了。安装程序在安装此软件包时遇到了意外错误。这可能表明行李有问题。...