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)
解决方案
使用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)
这将提高性能并且更容易阅读。
推荐阅读
- javascript - 在 React 上构建音频网站 - 解析错误
- caching - 如何正确处理无限重试后的榛子写入
- linux - ORA-12514 错误已更改为 ORA-12154?
- python - KivEnt 安装:致命错误 LNK1181 无法打开输入文件 'glew32.lib'
- apollo - 在 Apollo Link State 中存储数据数组
- bash - 如何按组将多个文件的内容附加到多个文件中
- javascript - AngularJS通过foreach替换列表中的元素
- c# - 在将组件添加到所有对象之前,如何设置刚体组件设置?
- html - 伪元素中的 Internet Explorer 材质图标不起作用
- azure-devops - dev.azure.com,可以添加用户,但不能更改密码