有什么办法可以删除包含两个具体字符串的两行之间的内容?
我的意思是:我想用以下文本删除文本文件中“天堂”和“地狱”之间的任何内容:
I'm in heaven
foobar
I'm in hell
执行脚本/函数后,我要求文本文件为空。
使用标志来指示您是否正在写作。
from __future__ import with_statement
writing = True
with open('myfile.txt') as f:
with open('output.txt') as out:
for line in f:
if writing:
if "heaven" in line:
writing = False
else:
out.write(line)
elif "hell" in line:
writing = True
os.remove('myfile.txt')
os.rename('output.txt', 'myfile.txt')
编辑
正如extraneon在评论中指出的那样,要求是删除两个具体字符串之间的线。这意味着如果永远找不到第二个(关闭)字符串,则不应删除任何内容。这可以通过保留行缓冲区来实现。如果找到关闭字符串"I'm in hell"
,则缓冲区将被丢弃,但如果到达文件末尾但没有找到它,则必须将全部内容写入文件。
例子:
I'm in heaven
foo
bar
应该保留全部内容,因为没有结束标签并且问题在两行之间。
这是一个完成此操作的示例:
from __future__ import with_statement
writing = True
with open('myfile.txt') as f:
with open('output.txt') as out:
for line in f:
if writing:
if "heaven" in line:
writing = False
buffer = [line]
else:
out.write(line)
elif "hell" in line:
writing = True
else:
buffer.append(line)
else:
if not writing:
#There wasn't a closing "I'm in hell", so write buffer contents
out.writelines(buffer)
os.remove('myfile.txt')
os.rename('output.txt', 'myfile.txt')
看起来“删除”是指“就地重写输入文件”(或者让它看起来像你这样做;-),在这种情况下fileinput.input 有帮助:
import fileinput
writing = True
for line in fileinput.input(['thefile.txt'], inplace=True):
if writing:
if 'heaven' in line: writing = False
else: print line,
else:
if 'hell' in line: writing = True
您可以使用正则表达式执行以下操作。可能有更有效的方法可以做到这一点,因为我还在学习很多 python,但这应该可行。
import re
f = open('hh_remove.txt')
lines = f.readlines()
pattern1 = re.compile("heaven",re.I)
pattern2 = re.compile("hell",re.I)
mark1 = False
mark2 = False
for i, line in enumerate(lines):
if pattern1.search(line) != None:
mark1 = True
set1 = i
if pattern2.search(line) != None:
mark2 = True
set2 = i+1
if ((mark1 == True) and (mark2 == True)):
del lines[set1:set2]
mark1 = False
mark2 = False
f.close()
out = open('hh_remove.txt','w')
out.write("".join(lines))
out.close()
我很抱歉,但这听起来像是一个家庭作业问题。我们对这些有政策:https ://meta.stackexchange.com/questions/10811/homework-on-stackoverflow
但是,我可以说@nosklo 所写的特性在任何 Python 2.5.x(或更高版本)中都可用,但您需要学习足够的 Python 才能启用它。:-)
str.find()
我的解决方案将涉及使用创建一个新字符串,并使用或str.index()
(或这两个的一些相对)去除不想要的东西。
祝你好运!
见下文。我不知道它是否正常,但它似乎工作正常。
import re,fileinput,os
for path, dirs, files in os.walk(path):
for filename in files:
fullpath = os.path.join(path, filename)
f = open(fullpath,'r')
data = f.read()
patter = re.compile('Im in heaven.*?Im in hell', re.I | re.S)
data = patter.sub("", data)
f.close()
f = open(fullpath, 'w')
f.write(data)
f.close()
无论如何,当我执行它时,它会留下一个空白行。我的意思是,如果有这个功能:
public function preFetchAll(Doctrine_Event $event){
//Im in heaven
$a = sfContext::getInstance()->getUser()->getAttribute("passw.formulario");
var_dump($a);
//Im in hell
foreach ($this->_listeners as $listener) {
$listener->preFetchAll($event);
}
}
我执行我的脚本,我得到了这个:
public function preFetchAll(Doctrine_Event $event){
foreach ($this->_listeners as $listener) {
$listener->preFetchAll($event);
}
}
如您所见,“public...”和“foreach...”之间有一个空行。
为什么?
哈维