Python 3.x:移至下一行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15656817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 3.x : move to next line
提问by SaintCore
I've got a small script that is extracting some text from a .html file.
我有一个从 .html 文件中提取一些文本的小脚本。
f = open(local_file,"r")
for line in f:
searchphrase = '<span class="position'
if searchphrase in line:
print("found it\n")
That works fine for me(error handling will be imported later), my problem is that the text I want to extract follows 2 lines after the searchphrase. How can I move 2 lines down in the .html file ?
这对我来说很好用(稍后将导入错误处理),我的问题是我要提取的文本在搜索短语后跟随 2 行。如何在 .html 文件中向下移动 2 行?
采纳答案by Martijn Pieters
You can advance f(which is an iterable) by two lines by calling next()on it twice:
您可以f通过调用next()它两次来推进(这是一个可迭代的)两行:
with open(local_file,"r") as f
for line in f:
searchphrase = '<span class="position'
if searchphrase in line:
print("found it\n")
next(f) # skip 1 line
return next(f) # and return the line after that.
However, if you are trying to parse HTML, consider using a HTML parser instead. Use BeautifulSoup, for example.
但是,如果你试图解析HTML,请考虑使用HTML解析器来代替。例如,使用BeautifulSoup。
回答by Michael
This works nice for me:
这对我很有用:
f = open(local_file,"r")
found = -1
for line in f:
if found == 2:
print("Line: "+line);
break
elif found > 0:
found += 1
else:
searchphrase = '<span class="position'
if searchphrase in line:
print("found it")
found = 1
The input file was:
输入文件是:
bla
<span class="position">Hello</span>
blub
that's it
whatever
And the output of the program:
以及程序的输出:
found it
Line: that's it
Instead of calling breakyou may also reset foundto -1 to search for more occurences of the pattern...
除了调用break您还可以重置found为 -1 以搜索模式的更多出现...

