Python:使用匹配字符串输入的文本文件查找单词,而不使用whitesp

2024-09-27 07:20:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个函数,使用文本文件(例如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”

如何运行最后两个输出


Tags: 函数字符串inretxt密码forsearch
1条回答
网友
1楼 · 发布于 2024-09-27 07:20:11

可以将re.findall与包含words.txt中所有单词的交替模式一起使用:

import re
def filesearch(userstring):
    print('\n'.join(re.findall('|'.join(map(str.rstrip, open("words.txt"))), userstring, re.IGNORECASE)))

相关问题 更多 >

    热门问题