1

如何从文本文件中删除注释块,注释包含在#|and中|#\n

文件:

#|\n this is some sort of foo bar\n that I don't care about|#\nthen there is a foo bar sentence that I want but i don't want that foo bar in within the hex pipe pipe hex comment block.#| and even so, i don't want this section to appear|#\n with some crazy sentence...

期望的输出:

then there is a foo bar sentence that I want but i don't want that foo bar in within the hex pipe pipe hex comment block. with some crazy sentence...

除了以下之外,还有更好的方法来删除评论块吗?

txt = '''#|\n this is some sort of foo bar\n that I don't care about|#\nthen there is a foo bar sentence that I want but i don't want that foo bar in within the hex pipe pipe hex comment block.#| and even so, i don't want this section to appear|#\n with some crazy sentence...'''

pointer = 0
while pointer < len(txt):
    try:
        start = txt.index('#|',pointer)
        end = txt.index('|#\n',start)
        cleantxt+=txt[pointer:start]
        pointer = end+3
    except ValueError:
        cleantxt+=txt[pointer:]
        break
4

1 回答 1

1

您可以使用正则表达式

>>> import re
>>> txt = '''#|\n this is some sort of foo bar\n that I don't care about|#\nthen there is a foo bar sentence that I want but i don't want that foo bar in within the hex pipe pipe hex comment block.#| and even so, i don't want this section to appear|#\n with some crazy sentence...'''
>>> txt2 = re.sub(r'#\|.*?\|#', '', txt, flags=re.DOTALL)  # remove multiline comment
>>> txt2
"\nthen there is a foo bar sentence that I want but i don't want that foo bar in within the hex pipe pipe hex comment block.\n with some crazy sentence..."

您还可以strip()删除不需要的换行符。

于 2013-08-13T15:19:32.353 回答