【问题标题】:How to verify that a replace has occured with Python re.subn如何使用 Python re.subn 验证是否发生了替换
【发布时间】:2020-11-10 03:45:26
【问题描述】:

我找不到类似的问题,所以请随时将我引导到其他地方。

我正在尝试验证字符串是否已被替换。我以前使用 .replace() 函数,但它没有返回任何东西告诉我它已被替换。我被引导到 re.subn 方法,但我不太确定它是如何工作的。

这是我到目前为止所拥有的。我正在尝试逐行读取文件,当它找到要替换的字符串时,它会替换它,然后将计数增加 1。

i= 1
newfile=open(fileOutput,'w', encoding="utf8")
for line in open("tempFile.txt", encoding="utf8"):
    line, numReplacements=re.subn("text to find", "replacementText")
    newfile.write(line)  
    if numReplacements < 0:
         i+=1

任何帮助表示赞赏!

【问题讨论】:

    标签: python replace


    【解决方案1】:

    您缺少 principale 参数:应用替换的行

    line, numReplacements = re.subn("text to find", "replacementText", line)
    

    但你对它返回的内容是正确的:a 2-tuple containing (new_string, number)

    • new_string是替换最左边得到的字符串 源中模式的非重叠出现 替换repl的字符串。
    • number 是替换的次数。

    修复

    但是你需要改变两件事

    • 条件的顺序,如果替换次数为正则要添加
    • 一般来说,您可能有不止一个替换值,因此请使用该值与前一个值进行总结
    if numReplacements > 0:
         i += numReplacements 
    

    更好

    • 您可以删除if,因为与0 相加并不是真正的问题
    • 您可以使用with 子句打开文件,因此文件最后会自行关闭
    i = 0
    with open(fileOutput, 'w', encoding="utf8") as outfile, \
            open("tempFile.txt", encoding="utf8") as infile:
        for line in infile:
            line, numReplacements = re.subn("text to find", "replacementText", line)
            outfile.write(line)
            i += numReplacements
    

    【讨论】:

    • 非常感谢。我错过了第三个论点。我的签名也弄错了!谢谢!
    猜你喜欢
    • 2013-02-05
    • 2010-10-30
    • 2012-02-28
    • 1970-01-01
    • 2021-03-29
    • 2023-03-16
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多