简体   繁体   English

在f.read上过滤多个字符串

[英]Filtering for multiple strings on f.read

Ive been playing with various ways to filter multiple strings on f.read() . 我一直在玩各种方法来过滤f.read()上的多个字符串。 I cant seem to find one that works as Id expect it to, apart from multiple separate loops but I refuse to believe there isn't a more elegant solution. 我似乎无法找到一个像Id期望的那样工作,除了多个单独的循环,但我拒绝相信没有更优雅的解决方案。

I am trying to do something akin to: 我正在尝试做类似的事情:

if 'string' or 'string2' or 'string3' in f.read():

I have tried a few variations such as: 我尝试过一些变化,例如:

if ('string1', 'string2','string3') in f.read():

if f.read() ('string1', 'string2','string3'):

Of course I've not found a way that is working in the manner I would expect, and as google and the docs are failing to, could anyone enlighten me? 当然,我没有找到一种方式,以我期望的方式工作,并且谷歌和文档都没有,任何人都可以启发我吗?

After Kasramvd's enlightenment the below shows both elegance and function. 在Kasramvd的启蒙之后,下面展示了优雅和功能。 Take note of the finale line specifically. 特别注意结局线。

check_list = ['string1', 'string2', 'string3']
for filename in files:
     f = open(root + filename)
     fi = f.read()
     if any(i in fi for i in check_list):

You are close in your fist code but you need to use or between conditions not objects, so you can change it to following : 你在你的拳头代码接近,但你需要使用or条件之间没有对象,所以你可以把它改成如下:

with open('file_name') as f:
    fi = f.read()
    if 'string' in fi or 'string2' in fi or 'string3' in fi:

But instead of that you can use built-in function any : 但不是你可以使用内置函数any

with open('file_name') as f:
    fi = f.read()
    if any(i in fi for i in word_set)

And if you are dealing with a huge file instead of loading the whole of file content in memory you can check the existence of strings in each line with a function : 如果您正在处理一个巨大的文件而不是将整个文件内容加载到内存中,您可以使用函数检查每行中是否存在字符串:

def my_func(word_set):
    with open('file_name') as f:
        for line in f:
            if any(i in line for i in word_set):
                return True
        return False

You can take them in a list an then compare: 你可以把它们放在一个列表然后比较:

lst=['string','string2','string3']
any(l in f.read() for l in lst)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM