简体   繁体   English

如何用python修改的行替换包含某些字符串的行?

[英]how to replace a line containing certain string with a new modified line with python?

My input is: 我的输入是:

*PART, NAME=Part-Default
**
****************************** N O D E S *********************************
*NODE, NSET=ALLNODES
   1,    2.228570e-02,   -8.715290e-01
   2,    1.463382e-02,   -9.181792e-01
*INSTANCE, NAME=Part-Default_1, PART=Part-Default
*END INSTANCE

I want to replace all the fields with Part-Default or Part-Default_1 with Part-1. 我想用Part-Default或Part-Default_1替换Part-1的所有字段。

Output should be: 输出应为:

*PART, NAME=Part-1
**
****************************** N O D E S *********************************
*NODE, NSET=ALLNODES
   1,    2.228570e-02,   -8.715290e-01
   2,    1.463382e-02,   -9.181792e-01
*INSTANCE, NAME=Part-1, PART=Part-1
*END INSTANCE

What I propose: 我的建议:

lines = f.readlines()
i=0
while (i<len(lines)):
    temp=lines[i].strip().split(',')
    if (temp[1]=="NAME=Part-Default"):
        f.write(""temp"\n")
        temp[1]="NAME=Part-1"
    if (temp[1]=="NAME=Part-1_1"):
        temp[1]="NAME=Part-1"
        f.write(""temp"\n")
    if (temp[2]=="NAME=Part-Default"):
        temp[1]="NAME=Part-1"
        f.write(""temp"\n")
    else
        f.write(""temp"\n")

I am not sure about the writing commands. 我不确定编写命令。 May be we can directly replace the strings somehow. 也许我们可以以某种方式直接替换字符串。 regards 问候

You can run a regular expression replacement on the whole file. 您可以在整个文件上运行正则表达式替换。 You won't need to do this line-by-line unless you are dealing with truly huge files. 除非您要处理的是真正的大文件,否则无需逐行执行此操作。

import re

filename = "xxx.txt"
with open(filename, "r") as f:
    content = f.read()
new_content = re.sub(r"(\w+)=Part-(1(_1)?|Default(_1)?)", r"\1=Part-1", content)
with open(filename, "w") as f:
    f.write(new_content)
lines = f.readlines()
for line in lines:
    line.replace("Part-Default_1", "Part-1").replace("Part-Default", "Part-1")

That will replace ANY instance of Part-Default_1. 这将替换Part-Default_1的任何实例。 If you want to be more specific then you can use something like: 如果您想更加具体,则可以使用以下方法:

lines = f.readlines()
for line in lines:
    if line.find("$QUALIFIER"):
        line.replace("Part-Default_1", "Part-1").replace("Part-Default", "Part-1")

Make sure you change $QUALIFER to be something that will qualify which lines you want the replace done on. 确保将$ QUALIFER更改为可以限定要替换的行的内容。

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

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