Python正则表达式查找器放入字典

时间:2019-12-24 22:49:09

标签: python regex

编程尚不成熟,因此对我本人所缺乏的知识深表歉意。

在尝试推断电话的电话号码及其MAC地址的过程中,我在下面提供了一些示例数据,并将其放入LLDPLarge变量:

LLDPLarge = '''* Slot-1 Far-B65-2ND.1 # show lldp neighbours detailed | include (System Name: "regDN |: 08:00:0F)

  Port ID     : 08:00:0F:36:46:62
- System Name: "regDN 7335,MITEL 5340 IP"
  Port ID     : 08:00:0F:3E:56:1C
- System Name: "regDN 7383,MITEL 5340 IP"
  Port ID     : 08:00:0F:3C:12:B2
- System Name: "regDN 7270,MITEL 5340 IP"
  Port ID     : 08:00:0F:28:9C:22
- System Name: "regDN 7320,MITEL 5340 IP"'''

我想出的代码如下:

vartest1 = "(?<=System Name: \"regDN )(.*)(?=,)"
vartest2 = "([0-9A-F]{2}[:-]){5}([0-9A-F]{2})"
vartest3 = vartest1 + "|" + vartest2

for match in re.finditer(vartest3, LLDPLarge):
    sGroup = match.group()
    print('{}'.format(sGroup))

这是它创建的输出的样本,非常接近我想要的:

08:00:0F:36:46:62
7335
08:00:0F:3E:56:1C
7383
08:00:0F:3C:12:B2
7270
08:00:0F:28:9C:22
7320

我想做的就是将其输出到字典中,如下所示:

'08:00:0F:36:46:62' : '7335'
'08:00:0F:3E:56:1C' : '7383'
'08:00:0F:3C:12:B2' : '7270'
'08:00:0F:28:9C:22' : '7320'

这时我不确定该怎么办或者我的代码是否最优雅?

最感谢您的帮助。

非常感谢。

4 个答案:

答案 0 :(得分:1)

检查是否填写了group(1)group(2)。如果group(1)有一个值,则正则表达式匹配电话号码,否则匹配MAC地址。然后,您可以将其用作字典的键或值。

d = {}
for match in re.finditer(vartest3, LLDPLarge):
    if match.group(2):
        key = match.group()
    else:
        val = match.group()
        d[key] = val

print(d)

答案 1 :(得分:1)

from re import finditer
from itertools import islice

# LLDPLarge = ...

pattern_system = "(?<=System Name: \"regDN )(.*)(?=,)"
pattern_port = "([0-9A-F]{2}[:-]){5}([0-9A-F]{2})"
pattern = f"{pattern_system}|{pattern_port}"

d = {key.group(): value.group() for key, value in zip(*[finditer(pattern, LLDPLarge)] * 2)}

答案 2 :(得分:1)

这是一种简单的方法:

# Make a list with all the strings
everything = [match.group() for match in re.finditer(vartest3, LLDPLarge)]
# Pick every other one to get a list of just the MAC addresses
macs = everything[0::2]
# Same thing for the names
names = everything[1::2]

# Make a blank dictionary
dict = {}
# Fill the dictionary from our lists
for i in range(0, len(macs)):
    dict[macs[i]] = names[i]

print(repr(dict))

itertools解决方案比这更优雅,但这需要更少的python专业知识才能理解。

答案 3 :(得分:1)

如果LLDPLarge是问题中的字符串,则此示例:

import re

d = dict(re.findall(r'([\dA-F:]{17}).*?regDN (\d+)', LLDPLarge, flags=re.S))
print(d)

打印:

{'08:00:0F:36:46:62': '7335', '08:00:0F:3E:56:1C': '7383', '08:00:0F:3C:12:B2': '7270', '08:00:0F:28:9C:22': '7320'}