簡體   English   中英

查找、替換和連接字符串

[英]Find, Replace, and Concatenate strings

經過 5 年以上的不活動,我只是重新(學習)python; 雖然我一開始並不擅長這並沒有幫助......這就是我想要做的:

  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. 查找替換 - G00 與 G1
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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM