【问题标题】:Using regex with fileinput gives error in Python将正则表达式与文件输入一起使用会在 Python 中出现错误
【发布时间】:2016-11-30 21:47:01
【问题描述】:

这是我用来替换文件中某些文本的代码:

for line in fileinput.input(the_file,inplace=True):
    sys.stdout.write(line.re.sub('Begin.*?end', new_data))

这给了我以下错误:

AttributeError: 'str' 对象没有属性 're'

我想也许我可以像这样直接使用re.subpart:

sys.stdout.write(re.sub('Begin.*?end', new_data))

但这给了我错误:

TypeError: sub() 缺少 1 个必需的位置参数:'string'

如何在 Python 中使用带有 fileinput 的正则表达式来正确搜索和替换文本?

【问题讨论】:

    标签: python regex python-3.x python-3.5


    【解决方案1】:

    做事

    sys.stdout.write(re.sub('Begin.*?end', new_data, line))
    

    re.sub 的签名是 re.sub(pattern, repl, string, count=0, flags=0)

    【讨论】:

    • 它可以工作,但有一个问题。新文件现在在其原始每一行之后都有一个空行。
    • 我要搜索的文本是否只有一行而不是全部有关系吗?
    • 要解决空行问题,请将上面的替换为sys.stdout.write(re.sub('Begin.*?end', new_data, line.strip()))。至于文本的位置是否重要,我不是做出决定的人,这取决于你
    • 感谢 khredos,但它现在已经剥离了所有行。 :) 我只想保持这些行的原始格式。
    • @SanJeetSingh 这不再是原始问题的一部分,而是进一步实施的结果。我鼓励您提出一个关于如何用另一个字符串替换部分字符串的新问题。
    猜你喜欢
    • 2013-10-24
    • 2014-09-25
    • 2017-03-09
    • 2015-12-18
    • 2016-12-29
    • 2011-06-19
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多