我有这种文件(部分):
H DX = 615 DY = 425 DZ = 22.15 -AB C = 0 T = 0 R = 999 * MM /“def”BX = 2.5 BY = 452.5 BZ = 25; M20150710。
XBO X = 100 Y = 50 Z = 5 V = 1000 R = 0 x = 0 y = 0 D = 10 N =“P”F = 1;测试F1 / 10P。…
…
作为灵感,你可以做这样的事情:
for raw_line in f: line = raw_line.split() if not line: continue if line[0] == 'H': header = {} for entry in line[1:4]: name, value = entry.split('=') header[name] = float(value) elif line[0] == 'XBO': xbo = {} for entry in line[1:11]: name, value = entry.split('=') try: xbo[name] = int(value) except ValueError: xbo[name] = value[1:-1] # stripping of the ""
现在 header 包含您网域的扩展程序:
header
{'DX': 615.0, 'DY': 425.0, 'DZ': 22.15}
和 xbo 其他值:
xbo
{'D': 10, 'F': 1, 'N': 'P', 'R': 0, 'V': 1000, 'X': 100, 'Y': 50, 'Z': 5, 'x': 0, 'y': 0}
访问词典中的各个值:
>>> header['DX'] 615.0
您可以使用,而不是手动转换数据类型 ast. literal_eval 。此帮助程序函数采用表单列表 ['a=2', 'b="abc"'] 并转换成字典 {'a': 2, 'b': 'abc'} :
ast. literal_eval
['a=2', 'b="abc"']
{'a': 2, 'b': 'abc'}
import ast def dict_from_row(row): """Convert a list of strings in the form 'name=value' into a dict.""" res = [] for entry in row: name, value = entry.split('=') res.append('"{name}": {value}'.format(name=name, value=value)) dict_string = '{{{}}}'.format(', '.join(res)) return ast.literal_eval(dict_string)
现在解析文件变得更简单了:
for line in f: row = line.split() if not row: continue if row[0] == 'H': header = dict_from_row(row[1:4]) elif line[0] == 'XBO': xbo = dict_from_row(row[1:11])
结果:
>>> header {'DX': 615, 'DY': 425, 'DZ': 22.15} >>> xbo {'D': 10, 'F': 1, 'R': 0, 'V': 1000, 'X': 100, 'Y': 50, 'Z': 5, 'x': 0, 'y': 0}