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
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
總結
以上是生活随笔為你收集整理的python判断英文字母_Python判断两个单词的相似度的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: scanf_s 发送访问冲突_程序员如何
- 下一篇: python判断对象是否实例化_pyth