Python 在日志文件行中搜索多个关键字,返回的错误字符串全部找到
我正在尝试创建这个程序,它打开一个.gz文件并查找多个异常。当我只使用一个异常时,它正在工作。但我现在试图获得多个异常,但它不起作用 有人能帮忙吗Python 在日志文件行中搜索多个关键字,返回的错误字符串全部找到,python,python-2.7,Python,Python 2.7,我正在尝试创建这个程序,它打开一个.gz文件并查找多个异常。当我只使用一个异常时,它正在工作。但我现在试图获得多个异常,但它不起作用 有人能帮忙吗 import gzip with gzip.open((raw_input("Enter File Name :")), 'r') as f: x1 = ['REBINFO', 'cocaLc'] y1 = [False, False] x2 = ['dispute', 'peer', 'while', 'priorit
import gzip
with gzip.open((raw_input("Enter File Name :")), 'r') as f:
x1 = ['REBINFO', 'cocaLc']
y1 = [False, False]
x2 = ['dispute', 'peer', 'while', 'priority']
y2 = [False, False, False, False]
x3 = ['task cocaLc ASSERT failed', 'fhAssert', 'REBINFO', 'HARDREBOOT', '09.']
y3 = [False, False, False, False, False]
for line in f:
for i in range(0, len(x1)):
if (x1, x2, x3) [i] in line: #loop through x1, x2, x3 using index numbers
y1[i] = True
y2[i] = True
y3[i] = True
if all(y1): #if every search string was detected, every value in y1 should be true
print "Exception Found : " + "task cocaLc Requested reboot"
if all(y2): #if every search string was detected, every value in y2 should be true
print "\nException Found : " + "task tAlrmL1 Keep alive failed"
if all(y3): #if every search string was detected, every value in y3 should be true
print "\nException Found : task cocaLc ASSERT failed"
我相信此代码符合您的问题陈述。代码中的两个关键更改
import gzip
errors_to_find = (
('task cocaLc Requested reboot',
('REBINFO', 'cocaLc')),
('task tAlrmL1 Keep alive failed',
('dispute', 'peer', 'while', 'priority')),
('task cocaLc ASSERT failed',
('fhAssert', 'REBINFO', 'HARDREBOOT')),
)
found_exc = []
with gzip.open((raw_input("Enter File Name :")), 'r') as f:
for line in f:
for msg, key_words in errors_to_find:
# for each keyword, test if it is in line
if sum([kw in line for kw in key_words]) == len(key_words):
found_exc.append(msg)
for msg in found_exc:
print "Exception Found : %s" % msg
你的问题是什么?这个程序不起作用,正在寻找与我使用的逻辑相同的解决方案,感谢Jean的帮助。欢迎使用堆栈溢出!您可以学习并创建一个示例。这使我们更容易帮助你。你问题中的问题是“它不起作用”,这是非常广泛的。您需要描述您不希望发生的事情以及您希望发生的事情。请解释,您是否遇到运行时错误?你能举一个可重复的例子吗?你期望什么样的产出,你得到什么?你的程序的输入是什么?斯蒂芬。。。。谢谢你的帮助,实际上我想单独保存错误消息,我想为单独的错误打印单独的语句。示例:x1=['REBINFO','cocaLc'],x1表示这两个例外,如果这两个例外都存在,我想打印“缺陷”编号,由于我们业务的性质,我在这里没有提到,但该缺陷是唯一的。对于x2,相同=['Distive','peer','while','priority'],如果变量x2中的所有字符串都存在于文件中,则会出现另一个需要打印的唯一缺陷。这正是您需要消息以及与它们相关联的关键字在同一数据结构中的原因。随着关键字和相关消息的更改,随着时间的推移,这将使维护更加容易。