繁体   English   中英

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

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

我想在包含patternB的行中替换字符串,如下所示:

从:

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

至:

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

我有这样的代码:

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)

它不会按预期替换包含“ patternB”的行,而是在其下方添加新行,如下所示:

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

我该如何处理我的代码?

您可以使用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.将字符串转储到文件

当然是这样,因为您在for循环的开头添加了对虚拟对象的行,然后在“ if”语句中再次添加了修改后的版本。 另外,如果您对待其他事物,为什么还要检查模式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)

如果要逐行保留迭代器(对于大文件)

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

这比其他响应速度慢,但可以处理大文件。

这应该工作

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