2013-03-27 66 views
1

我有一個從.html文件中提取一些文本的小腳本。Python 3.x:移動到下一行

f = open(local_file,"r") 
for line in f: 
    searchphrase = '<span class="position' 
    if searchphrase in line: 
     print("found it\n") 

這對我來說工作正常(錯誤處理將在稍後導入),我的問題是,我想提取文本遵循searchphrase後2行。如何在.html文件中向下移動兩行?

回答

6

您可以通過調用它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

+0

Thx你。偉大的作品:) – SaintCore 2013-03-27 12:14:28

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你也可以將found重置爲-1以搜索更多模式的出現...