gpt4 book ai didi

python - 如何使用 python 从给定文件中提取行 block

转载 作者:行者123 更新时间:2023-12-01 02:57:11 25 4
gpt4 key购买 nike

我有一个这样的文件

grouping data-rate-parameters {
description
"Data rate configuration parameters.";
reference
"ITU-T G.997.2 clause 7.2.1.";

leaf maximum-net-data-rate {
type bbf-yang:data-rate32;
default "4294967295";
description
"Defines the value of the maximum net data rate (see clause
11.4.2.2/G.9701).";
reference
"ITU-T G.997.2 clause 7.2.1.1 (MAXNDR).";
}

leaf psd-level {
type psd-level;
description
"The PSD level of the referenced sub-carrier.";
}
}
}

grouping line-spectrum-profile {
description
"Defines the parameters contained in a line spectrum
profile.";

leaf profiles {
type union {
type enumeration {
enum "all" {
description
"Used to indicate that all profiles are allowed.";
}
}
type profiles;
}

这里我想提取每个叶子 block 。例如,叶最大净数据速率 block 是

leaf maximum-net-data-rate {
type bbf-yang:data-rate32;
default "4294967295";
description
"Defines the value of the maximum net data rate (see clause
11.4.2.2/G.9701).";
reference
"ITU-T G.997.2 clause 7.2.1.1 (MAXNDR).";
}

像这样我想提取

我尝试使用这段代码,这里基于大括号('{')的计数,我试图读取该 block

with open(r'file.txt','r') as f:
leaf_part = []
count = 0
c = 'psd-level'
for line in f:
if 'leaf %s {'%c in line:
cur_line=line
for line in f:
pre_line=cur_line
cur_line=line
if '{' in pre_line:
leaf_part.append(pre_line)
count+=1
elif '}' in pre_line:
leaf_part.append(pre_line)
count-=1
elif count==0:
break
else:
leaf_part.append(pre_line)

它适用于leaf max-net-data-rate,但不适用于leaf psd-level

在对leaf psd-level进行操作时,它也会显示出 block 线。

帮助我完成这个任务。

最佳答案

它只需要在你的break循环中进行简单的编辑,因为多个右括号'}'你的计数已经是负数,因此你需要用

更改该行
elif count<=0:
break

但它仍然在您的列表中附加多个大括号,因此您可以通过保留左括号的记录来处理它,我更改了代码如下:

with open(r'file.txt','r') as f:
leaf_part = []
braces_record = []
count = 0
c = 'psd-level'
for line in f:
if 'leaf %s {'%c in line:
braces_record.append('{')
cur_line=line
for line in f:
pre_line=cur_line
cur_line=line
if '{' in pre_line:
braces_record.append('{')
leaf_part.append(pre_line)
count+=1
elif '}' in pre_line:
try:
braces_record.pop()
if len(braces_record)>0:
leaf_part.append(pre_line)
except:
pass
count-=1
elif count<=0:
break
elif '}' not in pre_line:
leaf_part.append(pre_line)

以上代码的结果:

      leaf psd-level {
type psd-level;
description
"The PSD level of the referenced sub-carrier.";
}

关于python - 如何使用 python 从给定文件中提取行 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107260/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com