2016-01-23 24 views
2

我想生成一個JSON文件,然後我可以使用D3等工具來理解這個新網絡元素的不同命令。帶有重複元素到JSON的文本文件

Here is a sample of how each command will look like.

樣品中的每一行是一個命令。爲每個命令分組得到一個類似於輸出格式的「樹」將是非常有用的。

我曾嘗試:

import sys, time, thread, re, commands, os, json 

Extract = [] 
PL = "" 

def DoIt(text,PL): 
    if not text.strip() == PL.strip(): 
     if not text.strip() == "": 
      Extract.append(text.split()) 
      PL = text.strip() 


def ExecuteCmd(String): 
    (status,Data)=commands.getstatusoutput(String) 
    print ".", 

PL = "" 
LINES = open('pana', 'r').readlines() # Pana = https://en.wikipedia.org/wiki/Venezuelan_Spanish 
for i in LINES: 
    DoIt(i,PL) 
    PL = i 


ExecuteCmd("rm -rfv TreeTmp") 
ExecuteCmd("mkdir TreeTmp") 

for j in range((len(Extract))): 
    Command = "" 
    for i in range((len(Extract[j]))): 
     lASn = Extract[j][i] 
     MyStr = "<" 
     ReSearch = re.search(MyStr + "(.*)", lASn) 
     if ReSearch: 
      lASn = "NA-VA" 

     Command = Command + "/" + lASn 
     ExecuteCmd("mkdir TreeTmp" + Command) 


def path_to_dict(path): 
    d = {'name': os.path.basename(path)} 
    if os.path.isdir(path): 
     d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir(path)] 
    else: 
     d['type'] = "file" 
    return d 

with open('flare.json', 'w') as outfile: 
    json.dump(path_to_dict('./TreeTmp/'), outfile) 

我已經做噸搜索在StackExchange,大概解析這個二進制樹,然後分析他們回來,或者創建數組在數組中的元素,或者步行過創建的目錄樹(上面的破壞代碼)。我在確定正確的邏輯方面確實存在問題。或者做到這一點的最佳方式。

回答

0

如果你只是在尋找獨特的,並且順序無關緊要,你可以在Python中用字典詞典獲得一個很好的樹形表示,幾乎不費吹灰之力。

def add_items(tree, items): 
    if items[0] not in tree: 
     branch = {} 
     tree[items[0]] = branch 
    else: 
     branch = tree[items[0]] 
    if len(items) > 1: 
     add_items(branch, items[1:])  

tree = {} 
with open('commands.txt') as f: 
    for line in f: 
     items = line.strip().split() 
     add_items(tree, items) 

from pprint import pprint 
pprint(tree) 

輸出:

{'param-1': {'param-2': {'param-X': {'gateway': {'<name>': {'protocol': {'param-Xv1': {'dpd': {}}}, 
                  'protocol-common': {'fragmentation': {}, 
                       'nat-traversal': {}}}}, 
            'param-Z': {'ipsec-param-Z': {'<name>': {'ah': {'authentication': {}}, 
                       'esp': {'authentication': {}, 
                         'encryption': {}}, 
                       'lifesize': {}, 
                       'lifetime': {}}}, 
               'param-X-param-Z': {'<name>': {'A': {}, 
                       'B': {}, 
                       'C': {}, 
                       'D': {}}}}}}, 
      'param-3': {'param-3': {'ntp-servers': {}, 
            'param-5': {'param-6': {}}, 
            'update-schedule': {'global-protect-datafile': {'recurring': {'weekly': {}}}}}}}} 

如果你必須有你的問題說明,與名稱和兒童標籤的格式,這應該工作:

class Element(object): 
    def __init__(self, name, children=None): 
     self.name = name  
     self.children = [] if children is None else children 
    def to_dict(self): 
     d = {'name': self.name} 
     if self.children: 
      d['children'] = [c.to_dict() for c in self.children] 
     return d 

def add_items(children, items): 
    head, *tail = items 
    for child in children: 
     if child.name == head: 
      break 
    else: 
     child = Element(head) 
     children.append(child) 
    if tail: 
     add_items(child.children, tail) 

root = Element('root') 

with open('commands.txt') as f: 
    for line in f: 
     items = line.strip().split() 
     add_items(root.children, items) 

輸出:

{'children': [{'children': [{'children': [{'children': [{'children': [{'name': 'param-6'}], 
     'name': 'param-5'}, 
     {'name': 'ntp-servers'}, 
     {'children': [{'children': [{'children': [{'name': 'weekly'}], 
      'name': 'recurring'}], 
      'name': 'global-protect-datafile'}], 
     'name': 'update-schedule'}], 
     'name': 'param-3'}], 
    'name': 'param-3'}, 
    {'children': [{'children': [{'children': [{'children': [{'children': [{'children': [{'name': 'dpd'}], 
       'name': 'param-Xv1'}], 
      'name': 'protocol'}, 
      {'children': [{'name': 'nat-traversal'}, 
       {'name': 'fragmentation'}], 
      'name': 'protocol-common'}], 
      'name': '<name>'}], 
     'name': 'gateway'}, 
     {'children': [{'children': [{'children': [{'name': 'A'}, 
       {'name': 'B'}, 
       {'name': 'C'}, 
       {'name': 'D'}], 
      'name': '<name>'}], 
      'name': 'param-X-param-Z'}, 
      {'children': [{'children': [{'children': [{'name': 'encryption'}, 
       {'name': 'authentication'}], 
       'name': 'esp'}, 
       {'children': [{'name': 'authentication'}], 'name': 'ah'}, 
       {'name': 'lifetime'}, 
       {'name': 'lifesize'}], 
      'name': '<name>'}], 
      'name': 'ipsec-param-Z'}], 
     'name': 'param-Z'}], 
     'name': 'param-X'}], 
    'name': 'param-2'}], 
    'name': 'param-1'}], 
'name': 'root'} 
+0

謝謝,我會試一試 –

相關問題