python - 在 Python 中将正则表达式与 fileinput 结合使用会出现错误

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

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

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

这给了我以下错误:

AttributeError: 'str' object has no attribute 're'

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

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

但这给了我错误:

TypeError: sub() missing 1 required positional argument: 'string'

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

最佳答案

就这么做

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

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

关于python - 在 Python 中将正则表达式与 fileinput 结合使用会出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38603532/

相关文章:

python - 当某些键不是字符串时,如何将 Python dict 转换为 JSON?

python - 如何使用嵌套索引为数组元素分配新值?

regex - Rust程序中的正则表达式

regex - 正则表达式提取单词之前/之后的数字

python - 递归循环时的组列表

python - 从 python 中执行复杂的 python 脚本

python - Docker Python 脚本找不到文件

java - 如何在java中使用命名组读取csv输入?

python - 使用 Tweepy 发布带有 YouTube 视频 URL 的推文

Python - 迭代月份日期并打印自定义输出