4장 연습 문제 16번

15번 문제와 유사한 문제이다. 다른 점은 문자열이 주어진 것이 아니라 문자열을 urlopen 으로 가져 오는 것이다.

웹문서를 가져 오는 방법은
import urllib

s = urllib.urlopen('http://www.python.org/').read()
이다.

15번과 유사한 문제이기 때문에 15번 풀이인 print re.sub('<(.*?)>', '', s) 를 그대로 써 보면 문제가 생긴다.
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <title>Python Programming Language -- Official Website</title>
  <meta name="keywords" content="python programming language object oriented web free source" />
  <meta name="description" content="      Home page for Python, an interpreted, interactive, object-oriented, extensible
     programming language. It provides an extraordinary combination of clarity and
     versatility, and is free and comprehensively ported." />
이와 같은 부분이
  
  Python Programming Language -- Official Website
  
  <meta name="description" content="      Home page for Python, an interpreted, interactive, object-oriented, extensible
     programming language. It provides an extraordinary combination of clarity and
     versatility, and is free and comprehensively ported." />
이렇게 바뀌게 된다.

몇몇 태그들은 없어 졌지만 일부 태그는 남게 된다.

그 이유는 정규식에서 메타 문자인 . 이 /n 인 줄바꾸기 문자를 제외한 문자만 매치 하기 때문이다.

즉, 15번과는 다르게 줄바꾸기 문자가 태그에 들어가 있기 때문에 매치가 안된 것이다.

이것을 해결 하기 위해 . 문자를 그대로 쓰면서 re.DOTALL 모드로 실행 하면 된다.

그런데 sub 메소드에는 이러한 플래그(re.DOTALL) 를 받는 인수가 없다.

따라서 매치할 부분을 compile 메소드를 사용해서 미리 객체로 컴파일 한 다음 그것을 매치할 문자열로 설정 하면 된다.
import re
a = re.compile('<(.*?)>', re.S)    #re.S 는 re.DOTALL 과 같다.
print a.sub('', s)



  
  Python Programming Language -- Official Website
  
  
  

결과가 위처럼 바뀌게 된다.

댓글 없음:

댓글 쓰기

크리에이티브 커먼즈 라이선스