我是Python的新手,我已经写了一些代码,当我运行代码时,出现了一些编译错误。有人可以帮我找出问题所在。
这是我的temp.log文件中包含的内容:
06 May 19 03:40:35 3 abCodeClearTrap Error Clear Trap (agent: 12367a12,
chassis:12367a12, ErrIdText: ERROR ID TEXT, csssi: EXTIFG, clearedID:
0x089088394)
06 May 19 03:44:35 3 abCodeErrorTrap Error Trap (agent: 12368a15, chassis:
12368a15, ErrIdText: Skip this item, csssi: SSRSSR, clearedID:
0x089088394)
到目前为止,我有一些代码: #!/ usr / bin / python 汇入
with open('temp.log') as f:
lines = f.readlines()
data = []
for line in lines:
date = re.match(r'\d{2} \w+ \d{2}', lines).group(0)
time = lines.split()[3]
ids = lines.split()[4]
agent = re.search(r'agent:\s(.*?),', lines).group(1)
errID = re.search(r'ErrIdText:\s(.*?),', lines).group(1)
clear = re.search(r'clearedID:\s(.*?)\)', lines).group(1)
row = [date, time, ids, agent, errID, clear]
data.append(row)
for row in data:
print(row)
运行上面的代码时,我得到了:
Traceback (most recent call last):
File "./practice.py", line 10, in <module>
date = re.match(r'\d{2} \w+ \d{2}', lines).group(0)
File "/usr/lib64/pythong2.7/re.py", line 137, in match
return _compile(patter, flags).match(string)
TypeError: expected string or buffer
此外,如果我注释掉第10行,则遇到的下一个错误是:
Traceback (most recent call last):
File "./practice.py", line 11, in <module>
time = lines.split()[3]
AttributeError: 'list' object has no attribute 'split'
任何人都可以帮助我找出这些错误。
非常感谢
答案 0 :(得分:4)
正如错误所言,lines
是一个列表。大概您打算在整个for循环中使用line
。
date = re.match(r'\d{2} \w+ \d{2}', line).group(0)
time = line.split()[3]
...
答案 1 :(得分:1)
这是您代码的有效版本。一些拼写错误,例如line而不是lines和group()而不是group(0),但您做得很好。
import re
with open('temp.log') as f:
lines = f.readlines()
data = []
for line in lines:
date = re.match(r'\d{2} \w+ \d{2}', line).group()
time = line.split()[3]
ids = line.split()[4]
try:
agent = re.search(r'agent:\s(.*?),', line).group()
except:
agent = 'agent:'
try:
errID = re.search(r'ErrIdText:\s(.*?),', line).group()
except:
errID = 'ErrIdText:'
try:
clear = re.search(r'clearedID:\s(.*?)\)', line).group()
except:
clear = 'clearedID:'
row = [date, time, ids, agent, errID, clear]
data.append(row)
for row in data:
print(row)
编辑:添加尝试,除非在日志文件中找不到关键字
结果:
['06 May 19', '03:40:35', '3', 'agent: 12367a12,', 'ErrIdText: ERROR ID TEXT,', 'clearedID: 0x089088394)']
['06 May 19', '03:44:35', '3', 'agent: 12368a15,', 'ErrIdText: Skip this item,', 'clearedID: 0x089088394)']