gpt4 book ai didi

python - 更新文本文件python的多行

转载 作者:太空宇宙 更新时间:2023-11-04 10:53:01 24 4
gpt4 key购买 nike

有没有办法用python更新多行文本文件,我想删除两行之间的数据我的文本文件如下

Project
Post
<cmd> ---Some statements--
---Some statements---
Mycommand "Sourcepath" "DestPath"
</cmd>
Post
Lib
TargetMachine=MachineX86
Lib
Project
Post
<cmd> ---Some statements---
---Some statements---
Mycommand "Sourcepath" "DestPath"
</cmd>
Post
Lib
TargetMachine=MachineX64
Lib

我想删除cmd标签之间的所有内容。这样生成的文本文件应该如下所示

Project
Post
<cmd>
</cmd>
Post
Lib
TargetMachine=MachineX86
Lib
Project
Post
<cmd>
</cmd>
Post
Lib
TargetMachine=MachineX64
Lib

最佳答案

假设您可以一次将整个文件读入内存,我建议

import re
with open("input.txt") as infile, open("output.txt", "w") as outfile:
outfile.write(re.sub(r"(?s)<cmd>.*?</cmd>", "<cmd>\n</cmd>", infile.read()))

要只匹配其中包含 xcopy 的标签,您需要稍微扩展正则表达式:

import re
with open("input.txt") as infile, open("output.txt", "w") as outfile:
outfile.write(re.sub(
r"""(?sx)<cmd> # Match <cmd>.
(?: # Match...
(?!</cmd>) # (unless we're at the closing tag)
. # any character
)* # any number of times.
\bxcopy\b # Match "xcopy" as a whole word
(?:(?!</cmd>).)* # (Same as above)
</cmd> # Match </cmd>""",
"<cmd>\n</cmd>", infile.read())

关于python - 更新文本文件python的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12477721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com