【问题标题】:Recursively replace certain lines using regex in Python在 Python 中使用正则表达式递归替换某些行
【发布时间】:2018-09-30 08:17:39
【问题描述】:

我有一个文本文件,想要递归地替换所有包含一些正则表达式模式的行,然后将结果保存到一个新的文本文件中。输入文本文件有以下内容:

姓名1 184,743 184,439 14,305 姓名2 84,343 64,437 36,335 名称3 154,543 174,439 38,385

我想用上面的非空行填充所有空行(包括只有制表符和/或空格的行)。最终输出应如下所示:

姓名1 184,743 184,439 14,305 姓名1 184,743 184,439 14,305 姓名1 184,743 184,439 14,305 姓名1 184,743 184,439 14,305 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 姓名2 84,343 64,437 36,335 名称3 154,543 174,439 38,385 名称3 154,543 174,439 38,385 名称3 154,543 174,439 38,385 名称3 154,543 174,439 38,385

我尝试了这段代码,但我不知道如何使它工作,因为我是 Python 新手。正则表达式在 Notepad++ 中有效,但在 IDLE 中无效:

import re
fhand = open("/home/user1/Documents/inputtext.txt")
fout = open("/home/user1/Documents/outputtext.txt","w")

for line in fhand:
    re.sub("^(\S+.*)$(\n)^([\t ]+|)$","\1\2\1",line)
    fout.write(line)
fout.close()

【问题讨论】:

    标签: python regex loops


    【解决方案1】:

    您可以使用一个简单的循环来跟踪其中包含任何非空格的最后一行:

    last = '\n'
    for line in fhand:
        # if the line isn't empty after stripping all whitespaces
        if line.strip():
            # save this line into the variable last for later blank lines to copy from
            last = line
        # otherwise it's a blank line
        else:
            # and we should copy from the non-blank line saved in the variable last
            line = last
        fout.write(line)
    fout.close()
    

    【讨论】:

    • 非常感谢,它有效。代码看起来“简单”,但我就是不明白发生了什么。
    • 不客气。我已经用 cmets 中的解释更新了我的代码。
    猜你喜欢
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多