Skip to main content
 首页 » 编程设计

将plt文件转换为特定格式的gcode的Python代码

2025年01月19日10jyk

我想将一组坐标从一种文件格式转换为另一种文件格式。它适用于绘图机,例如绘图仪。 第一个文件是一个 plt 文件,如下所示:

PU-3410,7784;PD-3373,-2281;PU16705,7978;PD16435,5325; (继续数以千计的坐标)

我想将它转换成另一个具有这种格式的文本文件:

G01 X-3410 Y7784 Z1000
G01 X-3373 Y-2281 Z0
G01 X16705 Y7978 Z1000
G01 X-16435 Y5325 Z0

PU 表示 Pen Up(Gcode 中的 Z1000),PD 表示落笔(Z0)。 我是 python 的新手,我只知道如何为 Arduino 编码。 这段代码会很有帮助。我试图了解如何打开和写入文件,但我对这个项目来说太新手了,所以我想我会寻求帮助而不是放弃。 非常感谢任何帮助! 干杯, 皮埃尔

请您参考如下方法:

免责声明:这可能并不完美,但我想我已经解决了。

# Uncomment this to read the file... remember to change your variable names too 
# with open('input_filename', 'r') as file: 
#    file_text = file.read() 
 
sample_text = 'PU-3410,7784;PD-3373,-2281;PU16705,7978;PD16435,5325;' 
 
coordinates = sample_text.split(';') # Splits the overall text into smaller easier chunks 
 
with open('output_filename', 'a+') as output_file: # Create file handler for output file 
    for c in coordinates: 
        if c[:2] == 'PU': # Checks the value of the first two characters, and if it is PU, use Z1000 
            g_code = 'Z1000' 
        else: # Use Z0 otherwise  
            g_code = 'Z0' 
        c = c[2:] # chop off either PU or PD 
        tokens = c.split(',') # Get the numbers 
        if len(tokens) < 2: # if something isn't formatted right, exit. 
            break 
        output_file.write("G01 X{0} Y{1} {2}\n".format(tokens[0], tokens[1], g_code)) 

我做了几个关键假设,需要注意:

1) 输入文件中没有格式错误 2)所有行都以G01开头 3) 我不知道完整的规范,所以其他东西可能会关闭