Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 我想在文件中搜索三个字符串并键入';缺陷';仅当这两个字符串都存在时_Python 2.7 - Fatal编程技术网

Python 2.7 我想在文件中搜索三个字符串并键入';缺陷';仅当这两个字符串都存在时

Python 2.7 我想在文件中搜索三个字符串并键入';缺陷';仅当这两个字符串都存在时,python-2.7,Python 2.7,我有一个txt文件,上面有三个调试签名 x = 'task cocaLc Requested reboot' y = 'memPartFree' z = 'memPartAlloc' import re f = open('testfile.txt','r') searchstrings = ('task cocaLc Requested reboot', 'memPartFree', 'memPartAlloc') for line in f(): for word in s

我有一个txt文件,上面有三个调试签名

x = 'task cocaLc Requested reboot'
y = 'memPartFree'
z = 'memPartAlloc'

import re
f = open('testfile.txt','r')
searchstrings = ('task cocaLc Requested reboot', 'memPartFree',     'memPartAlloc')
for line in f():
    for word in searchstrings:
        if any (s in line for s in searchstrings):
            print 'defect'
我想创建一个短脚本来扫描文件并仅在这三个字符串都存在时打印“缺陷”。
我尝试用不同的方法创建,但无法满足要求。

首先,示例代码的第4行有一个小错误
f
不可调用,因此不应在其旁边使用括号

如果您有一个包含以下内容的文件:

task cocaLc Requested reboot
memPartFree
memPartAlloc
它将打印“缺陷”9次,因为您要为每行检查一次,为每个搜索字符串检查一次。三行乘以三个搜索字符串等于9

any()
函数将在文件包含至少一个定义的搜索字符串时返回
True
任何时间。因此,此代码将为每行打印一次“缺陷”,乘以您定义的搜索字符串数

为了解决这个问题,程序需要知道是否/何时检测到任何特定的搜索字符串。您可以这样做:

f = open('testfile.txt','r')

searchstrings = ['task cocaLc Requested reboot', 'memPartFree', 'memPartAlloc']
detections = [False, False, False]

for line in f:
    for i in range(0, len(searchstrings)):
        if searchstrings[i] in line: #loop through searchstrings using index numbers
            detections[i] = True
            break    #break out of the loop since the word has been detected

if all(detections): #if every search string was detected, every value in detections should be true
    print "defect"
在这段代码中,我们循环遍历行和搜索字符串,但是
detection
变量用于告诉我们在文件中检测到了哪些搜索字符串。因此,如果该列表中的所有元素均为true,则表示已在文件中检测到所有搜索字符串