0


Python判断两个单词的相似度

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

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

from random import sample, randint

def oneInAnother(one, another):

  1. '''用来测试单词one中有多少字母不属于单词another'''
  2. return sum((1 for ch in one if ch not in another))

def testPositions(one, another, positions):

  1. '''用来测试单词one中位置positions上的字母是否
  2. 与单词another中的相同字母具有同样的前后顺序'''
  3. #获取单词one中指定位置上的字母
  4. lettersInOne = [one[p] for p in positions]
  5. print(lettersInOne)
  6. #这些字母在单词another中的位置
  7. positionsInAnother = [another[p:].index(ch)+p for p, ch in zip(positions,lettersInOne) if ch in another[p:]]
  8. print(positionsInAnother)
  9. #如果这些字母在单词another中也具有相同的前后位置关系,返回True
  10. if sorted(positionsInAnother)==positionsInAnother:
  11. return True
  12. return False

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

  1. c1 = oneInAnother(one, another)
  2. c2 = oneInAnother(another, one)
  3. #计算比例,测试两个单词有多少字母不相同
  4. r = abs(c1-c2) / len(one+another)
  5. #测试单词one随机位置上的字母是否在another中具有相同的前后顺序
  6. minLength = min(len(one), len(another))
  7. positions = sample(range(minLength), randint(minLength//2, minLength-1))
  8. positions.sort()
  9. flag = testPositions(one, another, positions)
  10. #两个单词具有较高相似度
  11. if flag and r<rateNumber:
  12. return True
  13. 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

标签: 算法 python java

本文转载自: https://blog.csdn.net/dongfuguo/article/details/118704376
版权归原作者 dongfuguo 所有, 如有侵权,请联系我们删除。

“Python判断两个单词的相似度”的评论:

还没有评论