解析 txt 文件并保存在 python 变量中
Parse txt file and save in python variable
我有一个包含以下行的 txt 文件
term accept_1
protocol:: tcp
destination-port:: 24
term accept_2
protocol:: tcp
source-port:: 21
source-port-port:: 22
我想做的是:
对于每个术语,将协议保存在一个变量中,并将端口也保存在一个变量中(可能在一个数组中)。
我用 PLY (Python Lex-Yacc) 结束了我的研究,但我发现它对于我的需要来说过于复杂了。
我的实际代码:
with fileinput.FileInput(file_pol,inplace = True, backup ='.bak') as policy:
for line in policy:
if "destination-port::" in line:
extract_port = re.findall("\d+",line)
elif "source-port::" in line:
extract_port = re.findall("\d+",line)
上面的基本上可以工作,但我想念术语、协议、端口之间的关系。
使用字典中的字典。
from collections import defaultdict
policy_dict = defaultdict(dict)
for line in policy:
key, value = line.strip().split()
if key == 'term':
term = value
elif key.endswith('::')
policy_dict[term][key[:-2]] = value
我有一个包含以下行的 txt 文件
term accept_1
protocol:: tcp
destination-port:: 24
term accept_2
protocol:: tcp
source-port:: 21
source-port-port:: 22
我想做的是: 对于每个术语,将协议保存在一个变量中,并将端口也保存在一个变量中(可能在一个数组中)。
我用 PLY (Python Lex-Yacc) 结束了我的研究,但我发现它对于我的需要来说过于复杂了。
我的实际代码:
with fileinput.FileInput(file_pol,inplace = True, backup ='.bak') as policy:
for line in policy:
if "destination-port::" in line:
extract_port = re.findall("\d+",line)
elif "source-port::" in line:
extract_port = re.findall("\d+",line)
上面的基本上可以工作,但我想念术语、协议、端口之间的关系。
使用字典中的字典。
from collections import defaultdict
policy_dict = defaultdict(dict)
for line in policy:
key, value = line.strip().split()
if key == 'term':
term = value
elif key.endswith('::')
policy_dict[term][key[:-2]] = value