2016-12-15 3 views
0

마크 업에서 특정 문자열을 추출하여 저장하려고합니다 (이 줄에서보다 복잡한 처리를 위해). 그래서 예를 들어 말을, 나는 파일에서 줄을 읽은 현재 라인은 다음과 같습니다파이썬에서 특정 문자열을 추출하는 방법

<center><img border="0" src="http://www.world-of-waterfalls.com/images/Cascades_04_015L.jpg" WIDTH="500" HEIGHT="375" alt="Looking up the Merced River Canyon towards Bridalveil Fall from the Big Oak Flat Road" ***PINIT***></center><br clear="all"><br clear="all"> 

하지만 저장할 :

tempUrl = 'http://www.world-of-waterfalls.com/images/Cascades_04_015L.jpg' 

tempWidth = 500 

tempHeight = 375 

tempAlt = 'Looking up the Merced River Canyon towards Bridalveil Fall from the Big Oak Flat Road' 

은 어떻게 파이썬에서 것을하고 가겠어요 ?

감사

+0

문제를 해결하고 정규식이 없다고 말씀 드리겠습니다. 그것을 시도하는 것을 생각하지 마십시오. 나중에 머리를 친 것입니다. 데이터가 웹 소스에서 나온 것이라면 BeautifulSoup 또는 scrapy 또는 다른 "스크래핑"라이브러리를보십시오. 마크 업이 이미있는 경우 파서를 사용하여 노드를 탐색하고 속성 정보를 수집 할 수 있습니다. –

+0

['HTMLParser'] (https://docs.python.org/2/library/htmlparser.html) 또는 ['html.parser'] (https://docs.python.org/3.4/library/html). parser.html) 파이썬 버전에 따라 –

답변

3

여기에 몇 가지 접근 방식 넘어갈 수 있지만, 내가 확장하고 HTML에서 많은 문제를 처리 할 수있는 HTML 파서를 사용하는 것이 좋습니다.

>>> from bs4 import BeautifulSoup 
>>> string = """<center><img border="0" src="http://www.world-of-waterfalls.com/images/Cascades_04_015L.jpg" WIDTH="500" HEIGHT="375" alt="Looking up the Merced River Canyon towards Bridalveil Fall from the Big Oak Flat Road" ***PINIT***></center><br clear="all"><br clear="all">""" 
>>> soup = BeautifulSoup(string, 'html.parser') 
>>> for attr in ['width', 'height', 'alt']: 
...  print('temp{} = {}'.format(attr.title(), soup.img[attr])) 
... 
tempWidth = 500 
tempHeight = 375 
tempAlt = Looking up the Merced River Canyon towards Bridalveil Fall from the Big Oak Flat Road 
+0

마지막으로 bs4를 설치 한 후에 이것은 아름다운 해결책입니다. 감사! – Johnny

0

그리고 정규식 방법 : 다음 작업 BeautifulSoup와 예제

import re 

string = "YOUR STRING" 
matches = re.findall("src=\"(.*?)\".*WIDTH=\"(.*?)\".*HEIGHT=\"(.*?)\".*alt=\"(.*?)\"", string)[0] 
tempUrl = matches[0] 
tempWidth = matches[1] 
tempHeight = matches[2] 
tempAlt = matches[3] 

모든 값은 문자열하지만, ​​그래서 당신이 원하는 경우 캐스팅 ..

은 그리고 알고 정규식 사본/paste는 나쁜 생각입니다. 쉽게 실수가있을 수 있습니다.

관련 문제