将内容保持在一个模式与另一个模式之间

2024-10-01 22:41:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我想解析html内容,并保留从A到B的内容 例如:

some content1...
<!-- begin_here -->
some content2
<!-- end_here -->
some content3

将成为

<!-- begin_here -->
some content2
<!-- end_here -->

现在,我用sed来做:

sed '/begin_here/,/end_here/!d' file.html > file2.html

但是,为了跨平台的目的,我想使用python重写它。 我对python中的regex不是很熟悉。 能给我一些提示吗? 非常感谢:)


Tags: 目的内容herehtml跨平台somesedregex
2条回答

使用多行正则表达式

import re
pat = re.compile('''^<!  begin_here  >.*?<!  end_here  >$''', 
                 re.DOTALL + re.MULTILINE)

with open("file.txt") as f:
    print pat.findall(f.read())

不需要正则表达式也可以这样做,例如:

add_next = False # Do not add lines
# Until you encounter the first "start_here", which sets it to True
with open("file1.html", "r") as in_file:
    with open("file2.html", "w") as out_file:
        for line in in_file:
            if "end_here" in line: # or line.startswith("end_here") for example
                add_next = False
            if add_next:
                out_file.write(line)
            if "begin_here" in line:
                add_next = True

相关问题 更多 >

    热门问题