python:如何在没有空格的文本文件中查找单词

发布于 2020-02-13 01:42:26

我定义了一个方法,功能是从文本文件中(如:abc.txt)查找指定字符串。
该方法可以查找部分的字符串,但有些则不行。我尝试使用,循环每行然后正则re.findall,但没起作用,所以注释掉了。
请问如何完善呢?

#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("abc")
filesearch("super car")

查看更多

关注者
0
被浏览
606
1 个回答
莫小豆
莫小豆 2020-02-13
这家伙很懒,什么也没写!

你应该使用re.findall匹配整个文本的内容,而不是一行行匹配。

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

撰写答案

请登录后再发布答案,点击登录

发布
问题

分享
好友

手机
浏览

扫码手机浏览