打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python 比较两个文本的相似性,分词版。

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

#!/usr/bin/env python# -*- coding: utf-8 -*import refrom math import sqrt#You have to install the python libimport jiebadef 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 ratefile_reader('thefile.txt','thefile2.txt')#该片段来自于http://outofmemory.cn
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
如何获取指定文件夹下所有文件名称并写入列表
Python入门6:数据写入文件
pypdf Merging multiple pdf files into one pdf
Python第7课:不一样的新建文件
Python使用神经网络进行简单文本分类
python 比较2个文件内容
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服