如果我有一个.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)
使用
filter
可能不会显著加快脚本速度,但值得一提的是,下面是它的外观:IMO,
filter(lambda)
is ugly并且永远不应该使用。相反,请使用generator expression:但是,由于
results
在这两种情况下都被完全使用,因此使用语句更简单:您可以将其移动到
with
块并在行上循环,这样您就不必将整个文件读入内存:即将提高性能且更易于阅读
相关问题 更多 >
编程相关推荐