📅  最后修改于: 2023-12-03 14:52:40.127000             🧑  作者: Mango
在 Python 中找到两个相似的词有许多方法,例如:
difflib 模块可以用来计算两个任意序列的差异,并返回一个增量的列表,从而找到两个相似的词。
import difflib
def similar_words(word1, word2):
sequence_matcher = difflib.SequenceMatcher(None, word1, word2)
match = sequence_matcher.find_longest_match(0, len(word1), 0, len(word2))
if match.size == 0:
return False
else:
return word1[match.a: match.a + match.size]
word1 = "hello"
word2 = "hero"
result = similar_words(word1, word2)
if result:
print(f"The similar word is {result}")
else:
print("No similar words found")
输出结果:
The similar word is he
nltk(Natural Language Toolkit)是一款用于 Python 中自然语言处理的库。可以使用 nltk 库提供的 levenshtein_distance() 方法计算两个词之间的距离,从而找到相似的词。
from nltk.metrics.distance import levenshtein_distance
def similar_words(word1, word2):
distance = levenshtein_distance(word1, word2)
if distance <= 2:
return True
else:
return False
word1 = "hello"
word2 = "hero"
if similar_words(word1, word2):
print(f"{word1} and {word2} are similar words")
else:
print("No similar words found")
输出结果:
hello and hero are similar words
以上是两种在 Python 中找到两个相似的词的方法,根据实际需求选择适合自己的方法即可。