首页 > 解决方案 > 如果子字符串是字符串的一部分,则使用过滤器函数返回完整的字符串

问题描述

如果我有一个.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)

标签: pythonpython-3.x

解决方案


使用filter可能不会使脚本显着更快,但对于它的价值,它看起来像这样:

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

IMO,filter(lambda) 很丑陋,永远不应该使用。相反,使用生成器表达式

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)

将提高性能并且更容易阅读。


推荐阅读