查找、替换和连接字符串

Find, Replace, and Concatenate strings

我只是重新(学习)python 经过 5 年多的闲置;不过,我一开始并不擅长这件事也无济于事…… 这是我正在尝试做的事情:

  1. 在文件中找到一个字符串并将其替换为另一个字符串(G00 与 G1)
  2. 找到一行以特定字符串开头并在末尾连接字符串的所有实例
  3. 原始文件 aaaa.gcode 保持不变,所有更改都保存到 bbbb.gcode。

两组代码都按预期工作。我尝试了很多不同的方法来将两组代码添加在一起,但没有任何效果。

示例文件(C:\gcode\aaaa.gcode)

# start of file
some text
other text

# more text
G00 X1 Y1
G00 X2 Y2
# other text
G00 X3 Y3
G00 X4 Y4

#end of file

对于最终结果,我希望:

# start of file
some text
other text

# more text
G1 X1 Y1 Z0.3
G1 X2 Y2 Z0.3
# other text
G1 X3 Y3 Z0.3
G1 X4 Y4 Z0.3

#end of file

示例代码/结果

  1. 找到用 G1 替换 - G00
Code:
    with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
    for line in fin:
        if line.startswith('G00'):
            fout.write(line[:-1] + ' Z0.3' + '\r')
        else:
            fout.write(line)
Result:
# start of file
some text
other text

# more text
G1 X1 Y1
G1 X2 Y2
# other text
G1 X3 Y3
G1 X4 Y4

#end of file
  1. 连接字符串 - 如果行以 G00 开头,则添加 Z0.3
Code:
    with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
        for line in fin:
            if line.startswith('G00'):
                fout.write(line[:-1] + ' Z0.3' + '\r')
            else:
                fout.write(line)
Result
# start of file
some text
other text

# more text
G00 X1 Y1 Z0.3
G00 X2 Y2 Z0.3
# other text
G00 X3 Y3 Z0.3
G00 X4 Y4 Z0.3

#end of file

我已经尝试了下面代码的各种分支,但我总是收到以下错误消息:

with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
    for line in fin:
        if line.startswith('G00'):
            fout.write(line[:-1] + ' Z0.3' + '\r')
            fout = fout.replace('G00', 'G1')   # newly added line
        else:
            fout.write(line)
AttributeError: '_io.TextIOWrapper' object has no attribute 'replace'

您正在尝试对文件句柄执行 .replace - 这没有意义,您应该在 line 上执行,例如:

with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
    for line in fin:
        line = line.replace('G00', 'G1')
        if line.startswith('G00'):
            fout.write(line[:-1] + ' Z0.3' + '\r')
        else:
            fout.write(line)

另请注意,当且仅当行以 \r 分隔时,您的代码才能正常工作。

不能从fout替换,需要替换该行的内容。为什么要设置为等于 fout.replace('G00', 'G1') # newly added line 也没有意义。试试这个:

with open(r'C:\gcode\aaaa.gcode', 'r') as fin, open(r'C:\gcode\bbbb.gcode', 'w') as fout:
    for line in fin:
        if line.startswith('G00'):
            fout.write(line[:-1] + ' Z0.3' + '\r')
            new_line = line('G00', 'G1')   # newly added line
            # I believe you're trying to add this new line to the document
            fout.write(new_line)
        else:
            fout.write(line)