user = matches [1] object没有属性' __ getitem __#39; Python错误

时间:2014-07-24 14:33:57

标签: python regex parsing

运行时我的python脚本出错

['dc:9f:db:1a:60:62']

Traceback (most recent call last): File "search.py", line 26, in <module> user = matches[1] TypeError: 'callable-iterator' object has no attribute '__getitem__'

我的脚本如下

import re

austins_mac_address = "f8:27:93:88:1c:95"

dd = {'f8:27:93:88:1c:95' : 'Austin iPhone', 'dc:9f:db:1a:60:64' : '4-Ops-AP', 'dc:9f:db:1a:60:62' : '4-TechOffices-AP', 'dc:9f:db:1a:61:b9' : '7-SalesReception-AP', 'dc:9f:db:1a:60:63' : '7-Marketing-AP', 'dc:9f:db:1a:61:bd' : '7-Sales-Engineers-AP', 'dc:9f:db:1a:60:f3' : '4-Dev-AP', 'dc:9f:db:1a:2c:dd' : '4-Hurricane-AP', '24:a4:3c:02:cf:f6' : '6-Meeting-AP', 'dc:9f:db:1a:60:ef' : '4-Lounge-AP', 'dc:9f:db:1a:61:ba' : '7-QA-AP', 'dc:9f:db:1a:60:5f' : '4-TechFloor-AP', 'dc:9f:db:1a:2d:95' : '4-training1-AP'}

dat = '[2014-07-22 10:21:06,821] <inform_stat-3> WARN event - [event] User[e4:98:d6:27:4c:b6] roams from AP[dc:9f:db:1a:60:64] to AP[dc:9f:db:1a:2d:95] on "channel 11(ng)"' aps = [] import re for line in open("server.log"): matches = re.finditer('(([0-9a-f]{2}[:-]){5}[0-9a-f]{2})', line) if matches: macAddrs = [] for match in matches: macAddrs.append(match.group(0)) print(macAddrs) user = matches[1] if (user.equals(austins_mac_address)): source = matches[3] dest = matches[5]

1 个答案:

答案 0 :(得分:1)

问题是matches是一个迭代器,因为那是re.finditer返回的。迭代器动态生成数据;它并非全部包含在数据结构中。这就是为什么你不能直接访问它的第二个元素。迭代器被设计为只循环一次(就像你在for match in matches那样),而不是随时访问随机元素。

如果您希望能够访问matches[1]等随机元素,则需要先遍历迭代器并将其所有数据存储在另一个列表中。

raw_matches = re.finditer('(([0-9a-f]{2}[:-]){5}[0-9a-f]{2})', line)
if raw_matches:
        matches = []
        for match in raw_matches:
                matches.append(match)

类似的东西,假设第一个对象在生成第二个对象时没有被销毁。