我想知道如何打印\begin 语句和\end 语句之间的所有文本。 这是我现在的代码。 另外,我怎样才能避免打印位于这两个语句之间的某些单词?
content=open("file", "r")
print content
content.read()
while len(content.split(start,1)) > 1:
start=("\begin")
end=("\end")
s=content
print find_between( s, "\begin", "\end" )
def find_between( s, first, last ):
try:
start = s.index( first ) + len( first )
end = s.index( last, start )
return s[start:end]
except ValueError:
return ""
print find_between( s, "\begin", "\end" )
请您参考如下方法:
此示例假定您不介意丢失 \begin 和 \end 行中的数据。它将打印 \begin 和 \end 之间所有出现的数据。
f = open("file", "r")
content = f.readlines()
f.close()
start = "\\begin"
end = "\\end"
print "Start ==", start, "End ==", end
printlines = False
for line in content:
if start in line:
printlines = True
continue
if end in line:
printlines = False
continue
if printlines == True:
print line
输入文件-
test
\begin do re me fa
so la te do.
do te la so \end fa me re do
输出-
Start == \begin End == \end
so la te do.
