繁体   English   中英

如何修复Python TypeError和AttributeError

[英]How to fix Python TypeError and AttributeError

我是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 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}', 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'

谁能帮助我找出这些错误。

提前谢谢了

就像错误都说的那样, lines是一个列表。 大概您打算在for循环中使用整个line

date = re.match(r'\d{2} \w+ \d{2}', line).group(0)
time = line.split()[3]
...

这是您的代码的工作版本。 一些拼写错误,例如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)']

暂无
暂无

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

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