0

我正在尝试在给定通配符模式的 Python 中搜索类似的单词,例如在类似于字典的文本文件中 - 我可以搜索 r?v?r? 正确的输出是“rover”、“raver”、“river”等词。这是我到目前为止的代码,但它仅在我输入完整单词而不是通配符形式时才有效。

name = input("Enter the name of the words file:\n"
pattern = input("Enter a search pattern:\n")`

textfile = open(name, 'r')
filetext = textfile.read()
textfile.close()
match = re.findall(pattern, filetext)
if match is True:
    print(match)
else:
    print("Sorry, matches for ", pattern, "could not to be found")
4

1 回答 1

0

使用点作为空白

name = input("Enter the name of the words file:\n"
pattern = input("Enter a search pattern:\n")`

textfile = open(name, 'r')
filetext = textfile.read()
textfile.close()
re.findall('r.v.r',filetext)
if match is True:
    print(match)
else:
    print("Sorry, matches for ", pattern, "could not to be found")

另外, match 是一个字符串,所以你想做 if match!=""或者if len(match)>0 ,无论哪个适合你的代码。

于 2020-06-23T14:13:58.573 回答