我正在尝试创建一个函数,使用文本文件(例如dictionary.txt)从没有空格的字符串中查找单词。它类似于从密码中检测单词
我的函数目前只接收一个字符串,它将从.txt文件中找到它并打印出来。我的问题目前没有从该字符串中找到任何其他单词。Regex可能是这里的解决方案,但我不知道如何从代码中实现它。我试着用regex使用forloop,但是没有用。我把它注释掉了,因为这条线似乎不起作用
这是我的密码:
#import re
def filesearch(userstring):
try:
filename = "words.txt"
with open(filename) as search:
for line in search:
line = line.rstrip()
# for word in re.findall(r'\w+', line):
if userstring.lower() == line.lower():
print("\nWords found in file: \n")
print(line)
except OSError:
print("ERROR: Cannot open file.")
filesearch("cars")
filesearch("holidays")
filesearch("runningaway")
filesearch("abcgobears124")
注意:最后两个输出将不运行
filesearch(“runningaway”)的输出应该打印单词“running”和“away”
对于filesearch(“abcgobears124”),输出应该打印单词“go”和“bears”
如何运行最后两个输出
可以将
re.findall
与包含words.txt
中所有单词的交替模式一起使用:相关问题 更多 >
编程相关推荐