我有这种文件(部分):
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 ;Test F1/10P.
...
我想将其转换为新的编程系统。我想要做的是首先读取标题(H)并将 DX、DY 和 DZ 值分别放入命名变量中。我设法做到了这一点,但是当我开始处理我的 XBO 线时(钻孔,我需要 X、Y、Z、V、R、x、y、D、N、F 和 ;,也在单独的变量中)我的代码很快就开始变得非常丑陋。
所以我重新开始,并想出了这个:
f = open("input.xxl") # open input file
for line in f:
if Debug==1: print line
for char in line:
charbuffr=charbuffr+char
if "H" in charbuffr:
if Debug==1: print'HEADER found!'
charbuffr=""
if "XBO" in charbuffr:
if Debug==1: print'XBO found!'
charbuffr=""
这正确地识别了单独的命令 H 和 XBO,但我现在有点卡住了。我可以使用相同的方法从 H 和 XBO 循环内的循环中提取所有变量,但这似乎不是很好的编码...
谁能让我迈出正确的一步吗?我不需要完整的解决方案,因为我喜欢编码(我的主要工作是为 CNC 机器编码,与 Python 相比,现在看起来很容易),但很想知道哪种方法最好......
最佳答案
您可以使用ast,而不是手动转换数据类型。文字评估。此辅助函数采用 ['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}
关于python - 将 CNC 钻孔从旧系统转换为新系统(使用 Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34101751/