0

我需要搜索一堆可能包含这种形式的内容的文本文件:

//for nv version
        tf = new TextField();
        tf.width = 600;
        tf.height = 300;
        tf.textColor = 0x00ffff;
        tf.mouseEnabled = false;
        this.addChild(tf);
        Sys.__consoleWindowFuncBasic = log;
//nv end

并删除两行之间的部分并保存。

我将文本分成几行,并逐行检查文本,从而使工作非常繁重,有没有简单的方法可以做到这一点?

4

2 回答 2

4

看一下这个

beginMarker = "//for nv version"
endMarker = "//nv end"

include = True
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    for line in infile:
        if include:
            if line.strip() != beginMarker:
                outfile.write(line)
            else:
                include = False
        else:
            if line.strip() == endMarker:
                include = True
于 2013-09-16T05:39:13.393 回答
2

也许您可以尝试使用正则表达式将匹配行替换为空行。@yuwang 提供了一个sed版本,这是一个python版本(python re docs):

>>> import re
>>> s = """some words
... other words
... //for nv version
...     tf = new TextField();
...     tf.width = 600;
...     tf.height = 300;
...     tf.textColor = 0x00ffff;
...     tf.mouseEnabled = false;
...     this.addChild(tf);
...     Sys.__consoleWindowFuncBasic = log;
... //nv end
... yet some other words
... """
>>> p = r"//for nv version(.*?)//nv end\n"  # reluctant instead of greedy
>>> print re.sub(p, "", s, flags=re.S) # use re.S to make `.` matchs `\n`
some words
other words
yet some other words
于 2013-09-16T06:29:43.567 回答