python - 使用 findall 替换并添加多行

标签 python regex python-3.x python-2.7 findall

我试图将多行添加到文件(input.txt)并替换同一文件(input.txt)中的多行,但我的代码仅在文件末尾插入行。你知道我如何修复代码以获得我想要的预期输出文件吗?

我的代码:

import re

searchtext1 = """
AB     3.483e-01   2.52e-02 ; 3.46 0.0123
"""
# add these lines after searchtext1
addtext1 = """
CD     2.123e-01   1.31e-02 ; 7.25 0.0145
DE     4.896e-01   7.25e-02 ; 8.25 0.0185
"""
searchtext2 = """
; atom
#atomnumber

#molecule
[weight]
"""
# replace these lines to searchtext2
changetext2 = """
; iron
#48kcal
35 mol
#12 g
"""

with open('input.txt', 'ab+') as infile:
    matches1 = re.findall(r'^(\d+)\.(.*)$', searchtext1, re.MULTILINE)
    infile.write(addtext1)

    matches2 = re.findall(r'^(\d+)\.(.*)$', searchtext2, re.MULTILINE)
    infile.write(changetext2)

输入.txt:

[atom]
123
[bonds]
XY     4.212e-01   4.18e-02 ; 8.01 0.0487
AB     3.483e-01   2.52e-02 ; 3.46 0.0123

[molecule]
1 2
3 4
TY     0.412e-01   1.72e-02 ; 0.32 0.0455

; atom
#atomnumber

#molecule
[weight]
calculated value is 5 kcal/mol
end file

预期输出文件:

[atom]
123
[bonds]
XY     4.212e-01   4.18e-02 ; 8.01 0.0487
AB     3.483e-01   2.52e-02 ; 3.46 0.0123
CD     2.123e-01   1.31e-02 ; 7.25 0.0145
DE     4.896e-01   7.25e-02 ; 8.25 0.0185

[molecule]
1 2
3 4
TY     0.412e-01   1.72e-02 ; 0.32 0.0455

; iron
#48kcal
35 mol
#12 g
calculated value is 5 kcal/mol
end file

最佳答案

正如 Chris 在评论中提到的,我建议尝试使用一个已经可以与格式交互的库 - configparser对我来说似乎是显而易见的选择,但如果格式可能与您问题中的内容不同,则可能有理由不这样做。

除此之外,如果您想使用 re ,我稍微更新了你的代码。这是我所做的调整:

  • 从三引号字符串的开头和结尾删除了换行符,因为它们将成为匹配的一部分,这可能是也可能不是您想要的。我个人的偏好是在实际替换中明确换行符。

  • 转义 []在您的搜索文本中,因为这些是 re 中的特殊字符并会混淆它(它们指定一个字符类)。

  • 二手with打开单独的输入和输出文件。当您退出 with 时,这些会被清除。堵塞。如果您确实想替换 input.txt,我想您可以稍后将 output.txt 移到顶部。

  • 您可以使用re.sub直接替换出现的内容,而不是搜索它们,在文本中查找索引,然后替换/追加。在添加文本的情况下,我刚刚将 searchtext1 进行了替换和addtext1 。 (我使用了 f 弦,但如果您愿意,也可以这样做 "{search}\n{add}".format(search=searchtext, add=addtext1)

  • 最后我们将更新后的文本写回光盘。

希望有帮助!

import re

searchtext1 = """AB     3.483e-01   2.52e-02 ; 3.46 0.0123"""
# add these lines after searchtext1
addtext1 = """CD     2.123e-01   1.31e-02 ; 7.25 0.0145
DE     4.896e-01   7.25e-02 ; 8.25 0.0185"""

searchtext2 = """; atom
#atomnumber

#molecule
\[weight\]"""
# replace these lines to searchtext2
changetext2 = """; iron
#48kcal
35 mol
#12 g"""

with open('input.txt', 'r') as infile, open("output.txt", "w") as outfile:
    intext = infile.read()

    intext = re.sub(searchtext1, f"{searchtext1}\n{addtext1}", intext)
    intext = re.sub(searchtext2, changetext2, intext)

    outfile.write(intext)

关于python - 使用 findall 替换并添加多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126527/

相关文章:

python - 由程序的用户创建类

python - 导入错误 : No module named win32service

c++ - 匹配C语言数字的正则表达式

PowerShell 中的正则表达式从 Active Directory 中的 Managedby 属性获取城市名称

python - 为什么不能添加 PPA 死蛇?

c++ - 在 C/C++ 中迭代 ndarray 列

python - 无法通过 PyPI 中的 pip 安装最新版本的软件包

python - Keras 的多维输入

php - 数据库表中的正则表达式搜索和替换

python-3.x - Selenium 通过 xpath 查找元素并单击