简体   繁体   English

替换在字符串中具有浮点数并写入新文件Python的变量

[英]Replace variable that has float in a string and writing to a new file Python

My question is about how to open a file, change a variable in a line. 我的问题是关于如何打开文件,更改一行中的变量。

Example: 例:

Modelica.SIunits.Height Hfsc = 3.7 "ground floor";

I need to change the Hfsc = 3.7 to Height_1 = 2 and then save the changes in a new file. 我需要将Hfsc = 3.7更改为Height_1 = 2 ,然后将更改保存在新文件中。 It should be something like this: 应该是这样的:

Modelica.SIunits.Height Height_1 = 2 "ground floor";

path = '/Users/project.mo'

with open(path, 'r') as f:

    for line in f:

        Height_1 = 2 # defined a variable
        float = 3.7 # do I need to define the 3.7 as a float?

        if "parameter Modelica.SIunits.Height Hfsc" in line:
            str2 = "Hfsc" print(line.find(str2))
            print(line.find('=', 37))
            print(line.find('"', 49))
            indices = [0, 44, 55]
            # indices to identify the splitting position of the string
            parts = [line[i:j] for i, j in zip(indices, indices[1:] [None])

            print(parts)

Output: 输出:

parameter Modelica.SIunits.Height ', 'Hfsc = 3.7 ', '"ground  floor";\n']

I can split the line, put I can't replace the variable Hfsc = 3.7 with Height_1 = 2 and write a new file. 我可以分割线,不能用Height_1 = 2替换变量Hfsc = 3.7并编写一个新文件。

I suggest that you use regular expressions for the substitution and then write to the file. 我建议您使用正则表达式进行替换,然后将其写入文件。 You could then simultaneously open two files, substitute and write to the new file like so: 然后,您可以同时打开两个文件,如下所示替换并写入新文件:

import re to_sub = 'parameter Modelica.SIunits.Height Hfsc = 3.7 "ground floor"' replacement = 'parameter Modelica.SIunits.Height Height_1 = 2 "ground floor"' with open(in_path, 'r') as inf, open(out_path, 'w') as outf: for line in inf: subbed_line = re.sub(to_sub, replacement, line) outf.write(subbed_line)

Hope you found this helpful! 希望对您有所帮助!

If the input is consistent enough, you should be able to simply do this: 如果输入足够一致,则应该可以简单地执行以下操作:

path = '/Users/project.mo'
newpath = '/Users/project_new.mo'

with open(path, 'r') as fin, open(newpath, 'w') as fout:
    for line in fin:
        if "parameter Modelica.SIunits.Height Hfsc = 3.7" in line:
            line = line.replace("Hfsc = 3.7", "Height_1 = 2")

        fout.write(line)

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

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