如何在python中查找和打印两个字符串之间的字符串?
我想知道如何打印\begin语句和\end语句之间的所有文本。 这是我现在的代码。 另外,我如何避免打印这两条语句之间的某些单词如何在python中查找和打印两个字符串之间的字符串?,python,string,printing,Python,String,Printing,我想知道如何打印\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"
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”块:
f = open('file', 'r')
between = ''
in_statement = False
for line in f:
if '\begin' in line:
in_statement = True
if in_statement:
between += line
if '\end' in line:
in_statement = False
break
print between
f.close()
本例假定您不介意丢失
\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.
regex适合做这类事情
In [152]: import re
In [153]: s = 'this is some \\begin string that i need to check \end some more\\begin and another \end stuff after'
In [167]: re.findall(r'\\begin(.*?)\\end', s)
[' string that i need to check ',
' and another ']
正则表达式:
使用原始字符串,因为\对正则表达式解析器有意义。
\begin和\ end是要匹配的原始字符串。必须执行两次反斜杠,因为反斜杠对正则表达式意味着“特殊”,所以需要\实际匹配反斜杠。
.*? = 点匹配任何内容,*表示匹配0个或更多重复。这个关闭贪婪行为-否则,它将匹配第一个开始和最后一个结束之间的所有内容,而不是匹配之间的所有内容
然后findall会给你一个所有匹配项的列表 您正在尝试处理latex文件吗?您当前的代码有什么问题?