我有一个小脚本,它从.html文件中提取一些文本。
f = open(local_file,"r")
for line in f:
searchphrase = '<span class="position'
if searchphrase in line:
print("found it\n")
这对我来说很好(稍后会导入错误处理),我的问题是我要提取的文本在搜索短语之后跟随2行。如何在.html文件中向下移动2行?
答案 0 :(得分:9)
您可以通过两次调用next()
将f
(这是一个可迭代的)推进两行:
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.
但是,如果您尝试解析HTML,请考虑使用HTML解析器而不是。例如,使用BeautifulSoup。
答案 1 :(得分:0)
这对我很有用:
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
输入文件是:
bla
<span class="position">Hello</span>
blub
that's it
whatever
程序的输出:
found it
Line: that's it
您可以将break
重置为-1,而不是调用found
来搜索模式的更多出现...