简体   繁体   English

替换行中的字符串而不添加新行?

[英]Replace string in line without adding new line?

I want to replace string in a line which contain patternB, something like this: 我想在包含patternB的行中替换字符串,如下所示:

from: 从:

some lines
line contain patternA
some lines
line contain patternB
more lines

to: 至:

some lines
line contain patternA
some lines
line contain patternB xx oo
more lines

I have code like this: 我有这样的代码:

inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []

for line in inputfile:
    dummy += line
    if line.find("patternA") != -1:
        for line in inputfile:
            dummy += line
            if line.find("patternB") != -1:
                item = line.split()
                dummy += item[0] + " xx " + item[-1] + "\n"
                break
outputfile.write(dummy)

It do not replace the line contain "patternB" as expected, but add an new line below it like : 它不会按预期替换包含“ patternB”的行,而是在其下方添加新行,如下所示:

some lines
line contain patternA
some lines
line contain patternB
line contain patternB xx oo
more lines

What can I do with my code? 我该如何处理我的代码?

You can use str.replace : 您可以使用str.replace

s = '''some lines
line contain patternA
some lines
line contain patternB
more lines'''

print(s.replace('patternB', 'patternB xx oo'))

最简单的方法是:1.将所有文件读入字符串2.调用string.replace 3.将字符串转储到文件

Of course it is, since you append line to dummy in the beginning of the for loop and then the modified version again in the "if" statement. 当然是这样,因为您在for循环的开头添加了对虚拟对象的行,然后在“ if”语句中再次添加了修改后的版本。 Also why check for Pattern A if you treat is as you treat everything else? 另外,如果您对待其他事物,为什么还要检查模式A?

inputfile = open("d:\myfile.abc", "r")
outputfile = open("d:\myfile_renew.abc", "w")
obj = "yaya"
dummy = ""
item = []

for line in inputfile:
    if line.find("patternB") != -1:
        item = line.split()
        dummy += item[0] + " xx " + item[-1] + "\n"
    else:
        dummy += line
outputfile.write(dummy)

If you want to keep line by line iterator (for a big file) 如果要逐行保留迭代器(对于大文件)

for line in inputfile:
    if line.find("patternB") != -1:
        dummy = line.replace('patternB', 'patternB xx oo')
        outputfile.write(dummy)
    else:
        outputfile.write(line)

This is slower than other responses, but enables big file processing. 这比其他响应速度慢,但可以处理大文件。

This should work 这应该工作

import os

def replace():

    f1 = open("d:\myfile.abc","r")
    f2 = open("d:\myfile_renew.abc","w")
    ow = raw_input("Enter word you wish to replace:")
    nw = raw_input("Enter new word:")
    for line in f1:
        templ = line.split()
        for i in templ:
            if i==ow:
                f2.write(nw)
            else:
                f2.write(i)
        f2.write('\n')
    f1.close()
    f2.close()
    os.remove("d:\myfile.abc")
    os.rename("d:\myfile_renew.abc","d:\myfile.abc")

replace()

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

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