简体   繁体   English

按行查找、乘法和替换字符串中的数字

[英]Find, multiply and replace numbers in strings, by line

I'm scaling the Gcode for my CNC laser power output.我正在为我的 CNC 激光功率 output 缩放 Gcode。 The laser's "S" value maxes at 225 and the current file scale is 1000. I need to multiply only/all S values by.225, omit S values of 0, and replace in the string for each line.激光的“S”值最大为 225,当前文件比例为 1000。我只需将/所有 S 值乘以 225,省略 0 的 S 值,并在每行的字符串中替换。 There are pre-designated "M", "G", "X", "Y", "Z", "F", and "S" in the Gcode for axis movement and machine functions. Gcode 中有预先指定的“M”、“G”、“X”、“Y”、“Z”、“F”和“S”,用于轴运动和机器功能。

Note: I can't do this manually as there's like 7.5k lines of code.注意:我不能手动执行此操作,因为有 7.5k 行代码。

Hoping for.py with an outcome like (top 3 lines):希望 for.py 的结果类似于(前 3 行):

Old> G1Y0.1S0     New> G1Y0.1S0
Old> G1X0.1S248   New> G1X0.1S55.8
Old> G1X0.1S795.3 New> G1X0.1S178.9

Example file Code:示例文件代码:

G1Y0.1S0
G1X0.1S248
G1X0.1S795.3
G1X0.2S909.4
G1X0.1S874
G1X0.1S374
G1X1.1S0
G1X0.1S610.2
G1X0.1S893.7
G1X0.6S909.4
G1X0.1S893.7
G1X0.1S661.4
G1X0.1S157.5
G1X0.1Y0.1S0
G1X-0.1S66.9
G1X-0.1S539.4
G1X-0.2S909.4
G1X-0.1S897.6
G1X-0.1S811
G1X-0.1S515.7
G1X-0.1S633.9
G1X-0.1S874
G1X-0.3S909.4
G1X-0.1S326.8
G1X-0.8S0

Tried this:试过这个:

import os
import sys
import fileinput

print("Text to Search For:")
textToSearch = input("> ")

print("Set Max Power Output:")
valueMult = input("> ")

print("File to work:")
fileToWork = input("> ")

tempFile = open(fileToWork, 'r+')

sValue = int

for line in fileinput.input (fileToWork):
    if textToSearch in line:
        c = str(textToSearch,(sValue)) #This is where I'm stuck.
        print("Match Found >> ", sValue)
    else:
        print("Match Not Found")
        
    tempFile.write(line.replace(textToSearch, (sValue,"(sValue * (int(valueMult)/1000))")))
    
tempFile.close()

#input("\n\n Press Enter to Exit")

Output: Output:

Text to Search For:
> S
Set Max Power Output:
> 225
File to work:
> test.rtf
Match Not Found
Traceback (most recent call last):
  File "/Users/iamme/Desktop/ConvertGcode.py", line 25, in <module>
    tempFile.write(line.replace(textToSearch, (sValue,"(sValue * (int(valueMult)/1000))")))
TypeError: replace() argument 2 must be str, not tuple
>>> 

test.rtf file:测试.rtf 文件:

Hello World

X-095Y15S434.5

That is Solid!

Your code has a couple of issues that need to be addressed:您的代码有几个问题需要解决:

  • first, you declare the sValue variable but never assign it the value from every line in your loop,首先,您声明sValue变量,但从不在循环中的每一行为其分配值,
  • second, said variable is an int, but should be a float or you'll lose the decimal part seen in the file,其次,所说的变量是一个整数,但应该是一个浮点数,否则你会丢失文件中看到的小数部分,
  • and third, since you're not getting the corresponding values, you're not multiplying the aforementioned values by the new scale factor to then replace the old with this.第三,由于您没有获得相应的值,因此您没有将上述值乘以新的比例因子,然后用这个替换旧的。

Additionally, you're opening the original file in read/write mode ( r+ ), but I would recommend you write to a new file instead.此外,您正在以读/写模式( r+ )打开原始文件,但我建议您改为写入新文件。

Now, here is your code with fixes and changes (I'm taking the liberty to write variable names in Python style):现在,这是您的代码,其中包含修复和更改(我冒昧地以 Python 样式编写变量名):

multiplier = input("New max power output for S: ")
input_file = input("Input file: ")
output_file = input("Output file: ")

with open(input_file, 'r') as source, open(output_file, 'w') as target:
    for line in source:
        if 'S' in line:
            line = line.removesuffix('\n')
            split_line = line.split('S', -1)
            new_value = float(split_line[1]) * float(multiplier)
            new_line = f'{split_line[0]}S{new_value:.1f}\n'
            print(f'Old> {line:25s}New> {new_line}', end='')
            target.write(new_line)
        else:
            target.write(line)

As you can see, we open both source and target files at the same time.如您所见,我们同时打开源文件和目标文件。 By using the with statement, the files are closed at the end of that block.通过使用with语句,文件在该块的末尾关闭。

The code assumes the text to search will appear no more than once per line.该代码假定要搜索的文本每行出现不超过一次。

When a match is found, we need to remove the newline from the line ( \n ) so it's easy to work with the number after the S .找到匹配项后,我们需要从行 ( \n ) 中删除换行符,以便使用S之后的数字。 We split the line in two parts (stored in the list split_line ), and convert the second element (S's value) to a float and multiply it by the entered multiplier.我们将线分成两部分(存储在列表split_line ),并将第二个元素(S 的值)转换为浮点数并将其乘以输入的乘数。 Then we construct the new line with its new value, print the old and new lines, and write it to the target file.然后我们用它的新值构造新行,打印旧行和新行,并将其写入目标文件。 We also write the line to the target file when a match isn't found so we don't lose them.当找不到匹配项时,我们还会将该行写入目标文件,这样我们就不会丢失它们。

IMPORTANT: this code also assumes no additional values appear after S{value} in the lines, as per your sample.重要提示:根据您的示例,此代码还假定行中的 S{value} 之后没有其他值出现。 If that is not the case, this code will fail when reaching those lines.如果不是这种情况,则此代码在到达这些行时将失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM