如果子字符串是字符串的一部分,则使用filter函数返回完整字符串

2024-09-30 22:23:41 发布

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

如果我有一个.txt文件,其中有随机字。 我想制作一个脚本,从给定的列表中读取文本并找到任何子字符串,然后返回子字符串所属的整个字符串。 这是否可以使用filter函数实现

我现在使用的功能没有filter函数,但是使用过滤器功能可能会使脚本运行得更快。如果可能的话,filter将是results的值

例如,我有一个.txt的内容是

Hello this is a test, redtreesarecool

接下来,我让它搜索任何包含单词tree的子字符串。我希望它返回redtreesarecool,因为tree是该字符串的子字符串

file_path = os.path.join(root, file)
try:
    with open(file_path, "r", encoding='utf-8', errors='ignore') as source_file:
        content = source_file.read().lower()
    results = [word for word in content.split() if any(sub in word for sub in search_strings)]

    if results:
        for result in results:
            print(file_path + ' | ' + result)
except OSError as e:
    print(file_path + ' | OSError', e)

Tags: path函数字符串in功能txt脚本tree
1条回答
网友
1楼 · 发布于 2024-09-30 22:23:41

使用filter可能不会显著加快脚本速度,但值得一提的是,下面是它的外观:

results = filter(lambda word: any(sub in word for sub in search_strings), content.split())

IMO,filter(lambda)is ugly并且永远不应该使用。相反,请使用generator expression

results = (word for word in content.split() if any(sub in word for sub in search_strings))
for result in results:
    print(result)

但是,由于results在这两种情况下都被完全使用,因此使用语句更简单:

for word in content.split():
    if any(sub in word for sub in search_strings):
        print(result)

您可以将其移动到with块并在行上循环,这样您就不必将整个文件读入内存:

with open(file_path) as source_file:
    for line in source_file:
        for word in line.lower().split():
            if any(sub in word for sub in search_strings):
                print(word)

将提高性能更易于阅读

相关问题 更多 >