我确实有这种格式的文本文件
instance_name = "small_instance_01_simple";
d = 2;
r = 3;
SCj = [80 57];
Dk = [96 22 14];
Cjk = [[81 51 31] [82 47 54]];
如何在python代码中获取这些变量的值?我尝试了更多方法,但未成功
答案 0 :(得分:3)
首先让我们导入re
并定义类似文件的对象:
import re
s = StringIO("""
instance_name = "small_instance_01_simple";
d = 2;
r = 3;
SCj = [80 57];
Dk = [96 22 14];
Cjk = [[81 51 31] [82 47 54]];
""")
parse_value
函数尝试将expr
解析为基元,如果它无法作为序列并最终作为字符串失败:
def parse_value(expr):
try:
return eval(expr)
except:
return eval(re.sub("\s+", ",", expr))
else:
return expr
parse_line
函数解析每一行并返回可变名称和值(如果有):
def parse_line(line):
eq = line.find('=')
if eq == -1: raise Exception()
key = line[:eq].strip()
value = line[eq+1:-2].strip()
return key, parse_value(value)
现在让我们提取变量:
vars = {}
for line in s.readlines():
try:
key, val = parse_line(line)
vars[key] = val
except:
pass
让我们检查一下我们拥有什么:
for key, value in vars.items():
print(key, value, type(value))
输出:
instance_name small_instance_01_simple <class 'str'>
d 2 <class 'int'>
r 3 <class 'int'>
SCj [80, 57] <class 'list'>
Dk [96, 22, 14] <class 'list'>
Cjk [[81, 51, 31], [82, 47, 54]] <class 'list'>