首先,我的示例文本文件的内容如下所示:
Some Data
Nothing important
Start here
This is important
Grab this line too
And this ono too
End here
Text goes on, but isn't important
Next text
Blaah
现在,我想在文本文件中阅读,我只想抓住" 从这里开始"和" 在此结束"。
所以我的Python代码如下:
filename = 'example_file.txt'
with open(filename, 'r') as input:
for line in input: # First loop breaks at specific line
if 'Start here' in line:
break
for line_1 in input: # Second loop grabs all lines
print line_1.strip()
for line_2 in input: # Third loop breaks at specific line
if 'End here' in line_2:
break
但它没有用。
这是我的输出,当我运行它时:
This is important
Grab this line too
And this on too
End here
Text goes on, but isn't important
Next text
Blaah
正如您所看到的,我的脚本并没有在结束此处中断。程序从正确的行开始,但它不会在正确的行中断。
出了什么问题?
答案 0 :(得分:3)
这是需要休息的第二个循环...
for line_1 in input:
if 'End here' in line_1:
break
print line_1.strip()
答案 1 :(得分:1)
您的问题是,您应该检查“在此处结束”'在你的第二个循环中,因为第二个和第三个循环不同时运行。事实上,第三个循环甚至不会运行。
考虑到这一点,这段代码将起作用:
filename = 'mydata.txt'
with open(filename, 'r') as f:
for line in f:
if 'Start here' in line:
break
for line_1 in f:
if 'End here' in line:
break
else:
print line.strip()
但是,我们仍然可以进行一些优化:
break
之后的任何代码都无法运行,因此我们可以摆脱else
; open
默认使用读取模式。考虑到这一点,您的最终代码将如下所示:
filename = 'mydata.txt'
with open(filename) as f:
for line in f:
if 'Start here' in line:
break
for line in f:
if 'End here' in line:
break
print line.strip()
运行它,您将获得所需的输出:
This is important
Grab this line too
And this ono too
答案 2 :(得分:0)
您可以将正则表达式(re
模块)与re.DOTALL
选项一起使用,以便将换行视为常规字符。
import re
source = """Some Data
Nothing important
Start here
This is important
Grab this line too
And this ono too
End here
Text goes on, but isn't important
Next text
Blaah"""
# or else:
# source = open(filename, 'r').read() # or similar
result = re.search("Start here(.*)End here", source, re.DOTALL).group(1).strip()
print result
> This is important
> Grab this line too
> And this ono too
为什么会这样:
re.search
在某些字符串中查找模式; .*
表示“任何字符,任意次数”。需要在两个硬编码标记之间取得所有内容(即Start Here
和End here
); re.DOTALL
是秘密:它会将换行字符视为常规字符串字符。 Dot是“任何字符”的符号,因此“全点”表示“将任何字符视为常规字符,甚至是新行字符”。group(1)
表示您需要第二个(从零开始的索引)组,它是括号内的组。答案 3 :(得分:0)
您可以先读取所有行并枚举它:
filename = 'example_file.txt'
useful_content = []
with open(filename, 'r') as input:
all_lines = input.readlines() # read all lines
for idx in range(len(all_lines)): # iterate all lines
if 'Start here' in all_lines[idx]:
useful_content.append(all_lines[idx].strip())
idx = idx + 1
# found start of useful contents, continue iterate till it ends
while 'End here' not in all_lines[idx]:
useful_content.append(all_lines[idx].strip())
idx = idx + 1
break
for line in useful_content:
print(line)