我需要搜索一堆文本文件,其中可能包含以下格式的内容:
//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
并删除2行之间的部分并保存。
我将文本分成几行,并逐行检查文本,从而使工作非常繁重,有没有简单的方法可以做到这一点?
答案 0 :(得分: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
答案 1 :(得分: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