0

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での正規表現にあまり慣れていません。これを行うためのヒントを教えてください。どうもありがとう :)

4

2 に答える 2

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())
于 2012-10-15T16:37:40.673 に答える
2

次のように、正規表現なしで実行できます。

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
于 2012-10-15T16:27:21.453 に答える