繁体   English   中英

搜索字符串数组的python循环在第一次迭代后中断

[英]A python loop that search array of strings breaks after first iteration

我有一个带有日志的文件。 每个日志位于一行。 我创建了一个搜索文件并将每个日志作为字符串查找的函数。 我订购了我希望作为数组/列表查找的日志。 目前,该函数根据列表中的第一项返回真/假。 例如,如果我要从文件中删除作为日志 #2 的项目 #2,该函数仍将返回 true,因为项目 #1 在文件中。 我希望我的循环将继续运行,直到搜索到列表中的所有项目。 这是我的实现:

def isClassDomainPassed():
    with open(NR_log, 'r') as logfile:

        key1 = 'The application is in Class Domain tab'
        key2 = 'Inspection Sampling is open'
        key3 = 'Golden Image was chosen'
        key4 = 'Accurate Navigation was chosen'
        key5 = 'Golden Image is enabled with Accurate Navigation'
        key6 = 'Location was added to Inspection Locations List'
        key7 = 'All dies were added to Inspection Dies List'
        keys = [key1, key2, key3, key4, key5, key6, key7]

        for key in keys:
            for num, line in enumerate(logfile, 1):
                if key in line:
                    return True, print("fine")
            return False, print("not")

isClassDomainPassed()

除非您每次都回到开头,否则您不能多次循环浏览该文件。 切换循环的顺序。 然后你也可以用any()替换key in keys的键。

False返回应该在循环之外,因此只有在通过所有循环时才这样做。

for line in logfile:
    if any(key in line for key in keys):
        print("fine")
        return True

print("not")
return False

如果我理解正确,您想检查日志文件中是否包含所有密钥。 如果是,该函数应返回True

def isClassDomainPassed(file_name):
    with open(file_name, "r") as logfile:
        data = logfile.read()

    key1 = "The application is in Class Domain tab"
    key2 = "Inspection Sampling is open"
    key3 = "Golden Image was chosen"
    key4 = "Accurate Navigation was chosen"
    key5 = "Golden Image is enabled with Accurate Navigation"
    key6 = "Location was added to Inspection Locations List"
    key7 = "All dies were added to Inspection Dies List"

    keys = [key1, key2, key3, key4, key5, key6, key7]

    return all(k in data for k in keys)


print(isClassDomainPassed("sample.txt"))

暂无
暂无

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

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