2013-03-27 3 views
1

.html 파일에서 일부 텍스트를 추출하는 작은 스크립트가 있습니다. 내가 추출 할 텍스트가 searchphrase 후 2 개 라인을 따르도록 (오류 처리가 나중에 가져옵니다) 나를 위해 잘 작동Python 3.x : 다음 줄로 이동

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

, 내 문제입니다. .html 파일에서 2 줄을 어떻게 아래로 이동할 수 있습니까?

답변

6

당신은 두 번에 next()를 호출하여 두 줄에 의해 (반복 가능하다) f을 향상 할 수 있습니다 당신은 HTML을 구문 분석하려는 경우

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 파서 사용을 고려. 예를 들어, BeautifulSoup을 사용하십시오.

+0

Thx 너. 위대한 작품 :) – SaintCore

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로 재설정하면 패턴이 더 많이 검색됩니다 ...

관련 문제