Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文本文件创建嵌套字典_Python - Fatal编程技术网

Python 从文本文件创建嵌套字典

Python 从文本文件创建嵌套字典,python,Python,我有上面的文本输出,我想创建一个嵌套字典,如下所示: 在上面的文本中,可能有两个以上的从属接口块 /tmp/bond0: Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011) Bonding Mode: IEEE 802.3ad Dynamic link aggregation Transmit Hash Policy: layer2+3 (2) MII Status: up MII Polling Interval (ms): 1

我有上面的文本输出,我想创建一个嵌套字典,如下所示: 在上面的文本中,可能有两个以上的从属接口块

/tmp/bond0:

Ethernet Channel Bonding Driver: v3.7.1 (April 27, 2011)

Bonding Mode: IEEE 802.3ad Dynamic link aggregation
Transmit Hash Policy: layer2+3 (2)
MII Status: up
MII Polling Interval (ms): 100
Up Delay (ms): 0
Down Delay (ms): 0

802.3ad info
LACP rate: slow
Min links: 0
Aggregator selection policy (ad_select): stable
Active Aggregator Info:
Aggregator ID: 2
Number of ports: 2
Actor Key: 11
Partner Key: 705
Partner Mac Address: 02:1c:73:9c:3c:fe

Slave Interface: p1p1
MII Status: up
Speed: 10000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 9c:dc:71:45:eb:80
Aggregator ID: 2
Slave queue ID: 0

Slave Interface: p4p1
MII Status: up
Speed: 10000 Mbps
Duplex: full
Link Failure Count: 0
Permanent HW addr: 9c:dc:71:4d:80:20
Aggregator ID: 2
Slave queue ID: 0
我开始做一些如下所示的编码,但仍然没有做到: #/usr/bin/python

从未来导入打印功能 导入pprint 导入操作系统 进口稀土 导入子流程

bond0 : {
 'MII Status:' : 'up',
 'Aggregator ID:' : '2',
 'Slave Interfaces' : { 'p1p1' : { 'MII Status' : 'up',
 'Permanent HW addr' : '9c:dc:71:45:eb:80',
 'MII Status' : up },
 'p4p1' : { ''MII Status' : 'up',
 'Permanent HW addr' : '9c:dc:71:4d:80:20',
 'MII Status' : up },
 },

我可能有更多的“bond”文件,即bond1、2、3、4等等。所以我认为有类更有意义,我转换成了类的形式。但它失败了。有什么想法吗

class BndClass(dict):
   def __init__(self, Bnd=None):
      self['Name'] = Bnd
      self.uPdateInfo()
      super(BndClass, self).__init__()

   def uPdateInfo(self):
      OutBnd = subprocess.Popen(['cat', '/tmp/'\
    + self['Name']],shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
      for line in OutBnd.stdout:
          match = re.search(r'^Cur.*?:\s+(.*?)$', line)
          if match:
              self['act_int'] = match.group(1)

          match = re.search(r'^\s*?Aggregator ID:\s+(\d)$', line)
          if match:
              self['agid'] = match.group(1)

          match = re.search(r'^Slave\sInterface:\s(.*?)$', line)
          if match:
              self.setdefault('slvs', []).append(match.group(1))


  if __name__ == '__main__':
      Y = BndClass('bond0')

  Y:

  {'Name': 'bond0', 'agid': '2', 'slvs': ['p1p1', 'p4p1']}
#/usr/bin/python
来自未来导入打印功能
从集合导入defaultdict
导入pprint
导入操作系统
进口稀土
导入子流程
类别BND类别(dict):
定义初始化(self,Bnd=None):
自我['Name']=Bnd
self.uPdateInfo()
超级(BndClass,self)。\uuuu init\uuuuu()
def更新信息(自身):
以open(self['Name'],“r”)作为f:
对于f中的行:
line=line.strip()#稍微清理一下:)
如果line.strip()==“”:继续
match=re.search(r'^\s*?(聚合器ID):\s+(\d)$,第行)
如果匹配:
self[match.group(1)]=match.group(2)
持续
match=re.search(r'^(从\n接口):\s(.*?$),第行)
如果匹配:
self[match.group(1)]=match.group(2)
尽管如此:
尝试:
行=下一个(f).strip()
除:
打破
如果行==“”:
打破
从属匹配=重新搜索(r'^(MII\sStatus):\s+(\w+$),行)
如果从站\u匹配:
self.setdefault(match.group(1),{}).setdefault(match.group(2),{})[slave\u match.group(1)]=slave\u match.group(2)
持续
从属匹配=重新搜索(r'^(永久\sHW\saddr):\s+(.+)$,第行)
如果从站\u匹配:
self.setdefault(match.group(1),{}).setdefault(match.group(2),{})[slave\u match.group(1)]=slave\u match.group(2)
持续
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
B=BndClass('bond0')
回溯(最近一次呼叫最后一次):
文件“/bc6.py”,第47行,在
B=BndClass('bond0')
文件“/bc6.py”,第14行,在__
self.uPdateInfo()
更新信息中第39行的文件“/bc6.py”
self.setdefault(match.group(1),{}).setdefault(match.group(2),{})
[从属匹配组(1)]=从属匹配组(2)
AttributeError:“str”对象没有属性“setdefault”

对不起,我开始了,然后做了其他事情,然后忘记了

这里有一个解决方案,它不是最性感的,但它仍然有效。如果您的文件具有非常严格的格式(看起来是这样),那么使用
break
continue
语句可以更高效地避免无用的正则表达式搜索

#!/usr/bin/python
from __future__ import print_function
from collections import defaultdict
import pprint
import os
import re
import subprocess



class BndClass(dict):
    def __init__(self, Bnd=None):
        self['Name'] = Bnd
        self.uPdateInfo()
        super(BndClass, self).__init__()

    def uPdateInfo(self):
        with open(self['Name'], "r") as f:
            for line in f:
                line = line.strip()  # clean that up a bit :)
                if line.strip() == "": continue
                match = re.search(r'^\s*?(Aggregator ID):\s+(\d)$', line)
                if match:
                    self[match.group(1)] = match.group(2)
                    continue

                match = re.search(r'^(Slave\sInterface):\s(.*?)$', line)
                if match:
                    self[match.group(1)] = match.group(2)
                    while True:
                        try:
                            line = next(f).strip()
                        except:
                            break
                        if line == "":
                            break
                        slave_match = re.search(r'^(MII\sStatus):\s+(\w+)$', line)
                        if slave_match:
                            self.setdefault(match.group(1), {}).setdefault(match.group(2), {})[slave_match.group(1)] = slave_match.group(2)
                            continue
                        slave_match = re.search(r'^(Permanent\sHW\saddr):\s+(.+)$', line)
                        if slave_match:
                            self.setdefault(match.group(1), {}).setdefault(match.group(2), {})[slave_match.group(1)] = slave_match.group(2)
                            continue

if __name__ == '__main__':
   B = BndClass('bond0')

Traceback (most recent call last):
File "./bc6.py", line 47, in <module>
    B = BndClass('bond0')
 File "./bc6.py", line 14, in __init__
   self.uPdateInfo()
 File "./bc6.py", line 39, in uPdateInfo
   self.setdefault(match.group(1), {}).setdefault(match.group(2), {}) 
 [slave_match.group(1)] = slave_match.group(2)
 AttributeError: 'str' object has no attribute 'setdefault'

这里我们使用一个
defaultdict
,它允许我们“根据请求创建密钥”,基本上如果您搜索一个不存在的密钥
defaultdict
将创建它,而不是引发错误

我将其中两个嵌套,因为我真正想要的是第二个,因为你最多有两个级别

from collections import defaultdict
final_dict = defaultdict(lambda: defaultdict(str))
这里有很好的解释,如果我的行是聚合器id,我就把它放在我的
定稿中注意围绕“聚合器id”添加的组。。然后,因为我知道我已经完成了这一行,所以我使用
continue
语句跳过循环的其余部分,继续下一行

...
match = re.search(r'^\s*?(Aggregator ID):\s+(\d)$', line)
if match:
        final_dict[match.group(1)] = match.group(2)
        continue
这里开始棘手的部分。如果前面的
匹配
失败(也称为行not聚合器id),那么我们尝试这一个,如果它不是从接口,我们只需循环下一行

...
match = re.search(r'^\s*?(Aggregator ID):\s+(\d)$', line)
if match:
        final_dict[match.group(1)] = match.group(2)
        continue
然而,如果是这一行,这意味着我们将输入一个从接口块,它将以一个空行结束(请稍后参阅)

这是我不得不使用
defaultdict
的原因,因为我将立即创建嵌套的dict
从接口:{p1p1p1':{}

...
match = re.search(r'^(Slave\sInterface):\s(.*?)$', line)
if match:
    final_dict[match.group(1)][match.group(2)] = {}
我们输入一个“子循环”,我用它来遍历从接口块,以查找您想要的条目(MII Status永久HW addr)。我们将在这个子循环(下面)中执行一些操作,但当我们找到一个空行时,这意味着我们已经完成了当前块的操作。(如果我们到达文件末尾,try-expect语句将在这里中断)

这与第一个
匹配
完全相同,我们寻找正确的行并将其添加到
最终dict
。但是我们需要使用另一个变量,因为我们需要
匹配
一个来访问dict中的正确位置



正如您所看到的,您离自己很近。不过,这种方法可能不是最好的。

我提出了以下解决方案,它可能会满足我的需要。谢谢

            ...
            if slave_match:
                final_dict[match.group(1)][match.group(2)][slave_match.group(1)] = slave_match.group(2)
                continue
            slave_match = re.search(r'^(Permanent\sHW\saddr):\s+(.+)$', line)
            if slave_match:
                final_dict[match.group(1)][match.group(2)][slave_match.group(1)] = slave_match.group(2)
                continue

你忘记了你想要的dict和最后一行的应答器(我不能编辑它们,因为“它大部分是代码”)您没有提供一个有效的最小示例,这对我来说很好,因为它解释得相当好,但在将来,您应该删除一个较小示例的一些部分。例如,删除不可用的类,并提供一个虚拟文件,而不是完整的文件(编写regex^^很烦人)很抱歉。下次会很用功:)非常感谢。是的,棘手的部分是while循环,我没有想到你是如何处理从块的。非常感谢。
            ...
            if slave_match:
                final_dict[match.group(1)][match.group(2)][slave_match.group(1)] = slave_match.group(2)
                continue
            slave_match = re.search(r'^(Permanent\sHW\saddr):\s+(.+)$', line)
            if slave_match:
                final_dict[match.group(1)][match.group(2)][slave_match.group(1)] = slave_match.group(2)
                continue
import re
import pprint
from collections import defaultdict

class AclassOfItwsOwn():
    def __init__(self, bond):
    self.bond = bond


def doIt(self):
    return self.MakeDict(self.bond)

@staticmethod
def MakeDict(bond):
    final_dict = defaultdict(lambda: defaultdict(str))

    with open(bond + '.txt', "r") as f:
        for line in f:
            line = line.strip()
            if line.strip() == "":
                continue
            match = re.search(r'^\s*?(Aggregator ID):\s+(\d)$', line)
            if match:
                final_dict[match.group(1)] = match.group(2)
                continue

            match = re.search(r'^(Slave\sInterface):\s(.*?)$', line)
            if match:
                final_dict[match.group(1)][match.group(2)] = {}
                while True:
                    try:
                        line = next(f).strip()
                    except:
                        break
                    if line == "":
                        break
                    slave_match = re.search(r'^(MII\sStatus):\s+(\w+)$', line)
                    if slave_match:
                        final_dict[match.group(1)][match.group(2)][slave_match.group(1)] = slave_match.group(2)
                        continue
                    slave_match = re.search(r'^(Permanent\sHW\saddr):\s+(.+)$', line)
                    if slave_match:
                        final_dict[match.group(1)][match.group(2)][slave_match.group(1)] = slave_match.group(2)
                        continue
    return final_dict

b0 = AclassOfItwsOwn('bond0')
b0.doIt()
b2 = AclassOfItwsOwn('bond2')
b2.doIt()