前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python判断两个单词的相似度

Python判断两个单词的相似度

作者头像
Python小屋屋主
发布2018-04-16 14:43:18
1.5K0
发布2018-04-16 14:43:18
举报
文章被收录于专栏:Python小屋Python小屋

本文要点在于算法的设计:如果两个单词中不相同的字母足够少,并且随机选择几个字母在两个单词中具有相同的前后顺序,则认为两个单词是等价的。

目前存在的问题:可能会有误判。

from random import sample, randint

def oneInAnother(one, another):

'''用来测试单词one中有多少字母不属于单词another'''

return sum((1 for ch in one if ch not in another))

def testPositions(one, another, positions):

'''用来测试单词one中位置positions上的字母是否

与单词another中的相同字母具有同样的前后顺序'''

#获取单词one中指定位置上的字母

lettersInOne = [one[p] for p in positions]

print(lettersInOne)

#这些字母在单词another中的位置

positionsInAnother = [another[p:].index(ch)+p for p, ch in zip(positions,lettersInOne) if ch in another[p:]]

print(positionsInAnother)

#如果这些字母在单词another中也具有相同的前后位置关系,返回True

if sorted(positionsInAnother)==positionsInAnother:

return True

return False

def main(one, another, rateNumber=1.0):

c1 = oneInAnother(one, another)

c2 = oneInAnother(another, one)

#计算比例,测试两个单词有多少字母不相同

r = abs(c1-c2) / len(one+another)

#测试单词one随机位置上的字母是否在another中具有相同的前后顺序

minLength = min(len(one), len(another))

positions = sample(range(minLength), randint(minLength//2, minLength-1))

positions.sort()

flag = testPositions(one, another, positions)

#两个单词具有较高相似度

if flag and r<rateNumber:

return True

return False

#测试效果

print(main('beautiful', 'beaut', 0.2))

print(main('beautiful', 'beautiful', 0.2))

print(main('beautiful', 'btuaeiflu', 0.2))

某次运行结果如下:

['a', 'u']

[2, 3]

False

['a', 'u', 'f', 'u']

[2, 3, 6, 7]

True

['b', 'e', 'a', 'u', 't', 'f']

[0, 4, 3, 8, 6]

False

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2016-09-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档