【问题标题】:Python 2.x find and replace multi line text [duplicate]Python 2.x 查找和替换多行文本 [重复]
【发布时间】:2014-11-06 02:22:49
【问题描述】:

我知道这里存在许多关于使用 python 2 查找和替换文件中的文本的问题。但是,作为 python 的新手,我不理解语法,可能目的也会有所不同。

我正在寻找一些非常简单的代码行,就像在 linux shellscript 中一样

sed -i 's/find/replace/' *.txt 
sed -i 's/find2/replace2/' *.txt

这段代码可以替换多行文本吗

with open('file.txt', 'w') as out_file:
   out_file.write(replace_all('old text 1', 'new text 1'))
   out_file.write(replace_all('old text 2', 'new text 2'))

另外,获取另一个换行符似乎有问题,我不想要。有什么想法或帮助吗?

【问题讨论】:

标签: python-2.7


【解决方案1】:

因此,对于 Python,最简单的做法是将文件中的所有文本读入字符串。然后使用该字符串执行任何必要的替换。然后将整个内容写回同一个文件:

filename = 'test.txt'

with open(filename, 'r') as f:
  text = f.read()

text = text.replace('Hello', 'Goodbye')
text = text.replace('name', 'nom')

with open(filename, 'w') as f:
  f.write(text)

replace 方法适用于任何字符串,并将第一个参数的任何(区分大小写)匹配替换为第二个。您正在读取和写入同一个文件,只是分两个不同的步骤。

【讨论】:

    【解决方案2】:

    这是一个快速示例。如果你想要更强大的搜索/替换,你可以使用正则表达式而不是 string.replace

    import fileinput
    for line in fileinput.input(inplace=True):
        newline = line.replace('old text','new text').strip()
        print newline
    

    将上面的代码放在一个想要的文件中,比如sample.py,假设你的python在你的路径中,你可以这样运行:

    python sample.py inputfile
    

    这将在输入文件中将“旧文本”替换为“新文本”。当然,您也可以将多个文件作为参数传递。见https://docs.python.org/2/library/fileinput.html

    【讨论】:

    • 如果我想替换 2 个不同的文本实例,那么这是否正确? newline = line.replace('old text 1','new text 1').strip() newline = line.replace('old text 2','new text 2').strip()我刚刚写了两行文本替换命令。
    • string.replace 将替换所有实例。如果您想限制有多少实例被替换,您可以指定另一个带有要替换的实例数量的参数。请参阅最底部的docs.python.org/2/library/string.html
    • 我想我并不清楚我想表达什么。我不是说要替换 n 实例,而是说替换 2 个或更多不同的文本行(如我在有问题的 sed 命令中所示。您引用的链接可以限制替换的次数文本。
    • 抱歉,我没有注意到,是的,您可以使用 line.replace 两次,然后打印一次
    • fileinput 是一个模块吗?我没有像你说的那样在终端中运行程序python sample.py inputfile,而是在另一个 python 程序中运行。在这种情况下,我必须读取一个文件。那么有什么变化呢?
    猜你喜欢
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 2022-07-13
    • 2016-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2016-09-22
    相关资源
    最近更新 更多