1

有没有办法使用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
4

1 回答 1

4

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

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())
于 2012-09-18T13:12:29.460 回答