A:我喜欢你
B: 我其实很喜欢你

对于文本相似度 = 2 * LCS(A,B)/ (len(A) + len(B))

目的: 字面衡量文本相似度的方法之一,涉及动态规划的思想

测试数据

苹果7手机图片	苹果7手机价格
汽车音响改装接线图	奥迪汽车音响改装
汽车音响改装接线图	汽车音响改装线路
如何才能让脸变白	怎样可以让皮肤变白
# -*- coding: utf-8 -*-
#!/usr/bin/python

import sys

def cal_lcs_sim(first_str, second_str):
    len_vv = [[0] * 50] * 50

    first_str = unicode(first_str, "utf-8", errors='ignore')
    second_str = unicode(second_str, "utf-8", errors='ignore')

    len_1 = len(first_str.strip())
    len_2 = len(second_str.strip())

    #print "len_1", len_1
    #print "len_2", len_2

    for i in range(1, len_1 + 1):
        for j in range(1, len_2 + 1):
            if first_str[i - 1] == second_str[j - 1]:
                len_vv[i][j] = 1 + len_vv[i - 1][j - 1]
            else:
                len_vv[i][j] = max(len_vv[i - 1][j], len_vv[i][j - 1])

    #print "lcs:", len_vv[i][j]
    return float(float(len_vv[len_1][len_2] * 2) / float(len_1 + len_2))


for line in sys.stdin:
    ss = line.strip().split('\t')
    if len(ss) != 2:
        continue
    first_str = ss[0].strip()
    second_str = ss[1].strip()

    sim_score = cal_lcs_sim(first_str, second_str)
    print '\t'.join([first_str, second_str, str(sim_score)])

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐