【问题标题】:Using regex in Python script [duplicate]在 Python 脚本中使用正则表达式 [重复]
【发布时间】:2019-07-13 13:21:34
【问题描述】:

我正在尝试编写一个 python 脚本来搜索和替换这一行:

时间剩余 3 总计

空行。

这是我的脚本:

import glob


read_files = glob.glob("*.agr")

with open("out.txt", "w") as outfile:
    for f in read_files:
        with open(f, "r") as infile:
            outfile.write(infile.read())

with open("out.txt", "r") as file:
    filedata = file.read()
filedata = filedata.replace(r'#time\s+residue\s+[0-9]\s+Total', 'x')
with open("out.txt", "w") as file:
    file.write(filedata)

使用这个,我无法得到任何替代品。为什么会这样?其余代码工作正常。输出文件没有改变,所以我怀疑找不到模式。

谢谢。

【问题讨论】:

    标签: python regex search replace


    【解决方案1】:

    str.replace 方法替换固定子字符串。如果您要替换正则表达式模式的匹配项,请改用 re.sub

    import re
    filedata = re.sub(r'#time\s+residue\s+[0-9]\s+Total', 'x', filedata)
    

    【讨论】:

    • 谢谢!这行得通!
    猜你喜欢
    • 2021-09-17
    • 2022-11-15
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2011-08-19
    • 2018-01-31
    • 1970-01-01
    • 2010-12-10
    相关资源
    最近更新 更多