返回顶部

收藏

比较两个文本的相似性,分词版。

更多

比较两个带有中文文本的相似性。实现到了分词以及余弦定理。

#!/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

标签:python,算法

收藏

0人收藏

支持

0

反对

0

»更多 您可能感兴趣的代码
  1. 2014-04-18 11:39:15python求解水仙花数 by 阮小七
  2. 2014-06-29 13:46:54Python中map filter reduce的递归实现 by 山药
  3. 2014-07-02 21:17:45输出100以内的素数 by jack.chen
  4. 2014-07-03 17:38:53解数独 by wubai
  5. 2014-07-13 15:18:02比较两文件的相似度(比较中文) by Solon.Ring
  6. 2014-08-22 13:23:01各种排序方法 by 蟋蟀MM
  7. 2014-09-08 14:56:48Python 动态规划算法,计算单词距离 by Solon.Ring
  8. 2013-06-04 13:43:27web.py中自定义jinja2模块 by 赵小全
  9. 2014-06-23 16:34:01更快速、准确、简单的中文摘要实现 by wubai
  10. 2014-07-06 14:00:15Python 相似单词 by 风云轩
  11. 2014-08-18 14:13:55Heapsort by 阮小七

发表评论