我是python的新手。我试图从树中访问信息。这是输入树:
+--rw service container
| +--rw downstream-data-rate-profile*(list) key : name
| | +--rw name type:bbf-yang:string-ascii64 + leaf
| | +--rw maximum-net-data-rate ? type:bbf-yang:data-rate32 + leaf
| | +--rw minimum-expected-throughput ? type:bbf-yang:data-rate32 + leaf
| | +--rw maximum-gamma-data-rate ? type:bbf-yang:data-rate32 + leaf
| | +--rw minimum-gamma-data-rate ? type:bbf-yang:data-rate32 + leaf
| +--rw time-division-duplexing-profile*(list) key : name
| +--rw name type:bbf-yang:string-ascii64 + leaf
| +--rw total-symbol-periods ? type:uint8 + leaf
| +--rw downstream-symbol-periods ? type:uint8 + leaf
| +--rw cyclic-extension ? type:uint8 + leaf
在上面的树中,'name'是一个叶子,'maximum-net-data-rate'是属于同一个列表的另一个叶子:'downstream-data-rate-profile'。
我的目标是将树叶划分为其所属列表。 例如:
[name,
maximum-net-data-rate,
minimum-expected-throughput,
maximum-gamma-data-rate,
minimum-gamma-data-rate]
是属于同一列表'downstream-data-rate-profile'的叶子列表。 我需要像这样划分。
这是我尝试过的代码:
with open('fast1.tree','r') as fl:
edit=''
f=[]
path=[]
clist=['container','list']
pl=''
f_cont=[]
comp=['default']
leaf_edit=[]
for i in fl:
f.append(i)
if 'leaf' in i:
cl=leaf_line=i
c=re.search(r'[\s]([\w/.-]+)',cl).group(1)
val=''
f_cont=[]
for line in f[::-1]:
for word in clist:
if word in line:
if space(cl)>space(line): #just comparing with the spaces
f_cont.append(line)
cl=line
for i in f_cont:
if 'list' in i:
c_l=i
b_list=re.search(r'[\s]([\w-]+)',i).group(1)
list_key = re.search(r'key :[\s]([\w-]+)',i).group(1)
comp.append(b_list)
break
if comp[-1]==comp[-2]: # if the last two elements are same i conclude that leaf belongs to same 'list'
edit = '%s '%(c)
leaf_edit.append(edit)
else:
if edit=='':
edit = '%s'%c
leaf_edit.append(edit)
continue
else:
print leaf_edit
leaf_edit=[]
edit = '%s'%c
leaf_edit.append(edit)
使用此代码,我可以打印第一个列表的叶子,但不能打印最后一个列表。 请帮帮我。