是否有一种方法可以在Python中组合两个列表进行搜索?



我想不出这个问题的标题,但我可以解释。假设用户必须输入一个包含两个单词的字符串。然而,每个单词都有多种写法。比如:

words = input("Enter 'Hello World' however you want to type it ")
possibilities = [
"Hello World",
"hello World",
"Hello world",
"hello world",
"Helo World",
"helo World",
"Helo world",
"helo world"
]
if words in possibilities:
print("true")

注意:

我知道这个特定的例子可以通过输入words.lower()来解决,并且你知道hello可能是一个严重的打字错误,它只是一个例子。

有办法这样做吗?

words = input("Enter 'Hello World' however you want to type it ")
firstWord = [
"Hello",
"hello",
"Helo",
"helo"
]
secondWord = [
"World",
"world",
]
words = words.split(' ')
if words[0] in firstWord and words[1] in secondWord:
print("true")

使用Levenshtein距离

请参阅https://tedboy.github.io/nlps/generated/generated/nltk.edit_distance.html#nltk-edit-distance作为python库的示例,该库将计算"Hello"one_answers"helo">

按要求回答问题,您可以使用itertools.product生成两个列表的所有组合。

from itertools import product

if words in [' '.join(t) for t in product(firstWord, secondWord)]:
print("true")

可以扩展:

parts = [["h", "H"], ["ello", "elo"], [" "], ["W", "w"], ["orld"]]
if words in [''.join(t) for t in product(*parts)]:
print("true")

最新更新