日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

python判断英文字母_Python判断两个单词的相似度

發布時間:2025/3/13 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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判断两个单词的相似度的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。