繁体   English   中英

如何在python中找到两个字符串之间的字符串并打印出来?

[英]How can I find and print a string between two strings in python?

我想知道如何打印\\ 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.

假设文件中只有一个“ \\ 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()

正则表达式对这种事情有好处。

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个或多个重复。 关闭贪婪的行为-否则,它将匹配FIRST开始和LAST结束之间的所有内容,而不是匹配之间的所有内容。

然后findall为您提供所有匹配项的列表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM