匹配包含文件python中的行的多个字符串

时间:2016-01-04 07:21:07

标签: python

我想匹配文件中的多个字符串。我如何在python中执行此操作?

目标:匹配两个值为" DC1" &安培; " TIER2"来自档案

我的代码,但匹配字符串对象

中的任何字符串
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        deltaa = data.readline().rstrip()
        print ("*********")
        for item in strings:
            if item in deltaa:
                print (deltaa)

1 个答案:

答案 0 :(得分:2)

使用all进行检查:

  

all(iterable)如果iterable的所有元素都为真(或   如果iterable为空)。相当于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        if all(x in deltaa for x in strings): #Check if all items in strings exit in deltaa
            print (deltaa)

如果您想检查strings中是否至少有一个deltaa使用any而是:

  

any(iterable)如果iterable的任何元素为true,则返回True。如果   iterable为空,返回False。相当于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        if any(x in deltaa for x in strings): #Check if any item in strings exits in deltaa
            print (deltaa)