【问题标题】:create a dictionary from file python从文件 python 创建字典
【发布时间】:2018-03-29 15:14:37
【问题描述】:

我是 python 新手,正在尝试读取文件并从中创建字典。 格式如下:

.1.3.6.1.4.1.14823.1.1.27 {
    TYPE = Switch
    VENDOR = Aruba
    MODEL = ArubaS3500-48T
    CERTIFICATION = CERTIFIED
    CONT = Aruba-Switch
    HEALTH = ARUBA-Controller
    VLAN = Dot1q    INSTRUMENTATION:
     Card-Fault            = ArubaController:DeviceID
     CPU/Memory            = ArubaController:DeviceID
     Environment              = ArubaSysExt:DeviceID
     Interface-Fault       = MIB2
     Interface-Performance = MIB2
     Port-Fault            = MIB2
     Port-Performance      = MIB2 
}

第一行 OID (.1.3.6.1.4.1.14823.1.1.27 { ) 我希望这是关键,其余行是直到 }

我尝试了一些组合,但无法获得正确的正则表达式来匹配这些

有什么帮助吗?

我尝试过类似的东西

lines = cache.readlines()

for line in lines:

    searchObj = re.search(r'(^.\d.*{)(.*)$', line)

    if searchObj:
        (oid, cert ) = searchObj.groups()

    results[searchObj(oid)] = ", ".join(line[1:])

    print("searchObj.group() : ", searchObj.group(1))

    print("searchObj.group(1) : ", searchObj.group(2))

【问题讨论】:

  • 是的,它总是 .1.3.6.1.4.x.x.x.x

标签: python regex dictionary


【解决方案1】:

你可以试试这个:

import re
data = open('filename.txt').read()
the_key = re.findall("^\n*[\.\d]+", data)
values = [re.split("\s+\=\s+", i) for i in re.findall("[a-zA-Z0-9]+\s*\=\s*[a-zA-Z0-9]+", data)]
final_data = {the_key[0]:dict(values)}

输出:

{'\n.1.3.6.1.4.1.14823.1.1.27': {'VENDOR': 'Aruba', 'CERTIFICATION': 'CERTIFIED', 'Fault': 'MIB2', 'VLAN': 'Dot1q', 'Environment': 'ArubaSysExt', 'HEALTH': 'ARUBA', 'Memory': 'ArubaController', 'Performance': 'MIB2', 'CONT': 'Aruba', 'MODEL': 'ArubaS3500', 'TYPE': 'Switch'}}

【讨论】:

    【解决方案2】:

    您可以使用 嵌套字典理解 以及外部和内部正则表达式。


    您的块可以通过
    .numbers...numbers.. {
        // values here
    }
    

    就正则表达式而言,这可以表述为

    ^\s*                 # start of line + whitespaces, eventually
    (?P<key>\.[\d.]+)\s* # the key
    {(?P<values>[^{}]+)} # everything between { and }
    

    如您所见,我们将部分拆分为键/值对。


    您的“内部”结构可以表述为
    (?P<key>\b[A-Z][-/\w]+\b) # the "inner" key
    \s*=\s*                   # whitespaces, =, whitespaces
    (?P<value>.+)             # the value
    


    现在让我们一起构建“外部”和“内部”表达式:
    rx_outer = re.compile(r'^\s*(?P<key>\.[\d.]+)\s*{(?P<values>[^{}]+)}', re.MULTILINE)
    rx_inner = re.compile(r'(?P<key>\b[A-Z][-/\w]+\b)\s*=\s*(?P<value>.+)')
    
    result = {item.group('key'): 
        {match.group('key'): match.group('value') 
        for match in rx_inner.finditer(item.group('values'))} 
        for item in rx_outer.finditer(string)}
    print(result)
    

    demo can be found on ideone.com

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 2012-03-08
      • 1970-01-01
      • 2013-07-13
      • 2016-09-03
      • 2021-05-10
      • 2021-05-15
      相关资源
      最近更新 更多