2013-07-27 2 views
0

항목 1, 항목 2 및 항목 3이있는 html 파일을 작성 중입니다. 마지막 항목 2 이후에 나오는 텍스트를 모두 삭제하고 싶습니다. 파일에 2 개 이상의 항목이 있어야합니다. 나는 이것을 사용하고 있지만 작동하지 않습니다파이썬에서 html 파일의 특정 부분을 제거하는 방법

text = """<A href="#106">Item&nbsp;2. <B>Item&nbsp;2. Properties</B> this is an example this is an example""" 

>>> a=re.search ('(?<=<B>)Item&nbsp;2.',text) 
>>> b= a.group(0) 
>>> newText= text.partition(b)[0] 
>>> newText 
'<A href="#106">' 

그것은 첫 번째 항목이없는 두 번째 이후의 텍스트를 삭제합니다.

+0

당신은 당신이 기대하는 문자열을 제시해주십시오 수있는 특정 예를 들어

너의 질문? – nio

+0

가장 높은 투표 응답을 읽으십시오. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Hyperboreus

답변

1

BeautifulSoup을 사용하여 HTML을 구문 분석하고 수정하십시오. decompose() 또는 extract() 메서드를 사용할 수 있습니다.

BeautifulSoup는 조작 된 HTML을 구문 분석하는 데 효과적이므로 훌륭합니다. 당신이 정말로 싶어 정규 표현식을 사용하는 경우

>>> import bs4 
>>> text = """<A href="#106">Item&nbsp;2. <B>Item&nbsp;2. Properties</B> this is an example this is an example""" 
>>> soup = bs4.BeautifulSoup(text) 
>>> soup.b.next_sibling.extract() 
u' this is an example this is an example' 
>>> soup 
<html><body><a href="#106">Item 2. <b>Item 2. Properties</b></a></body></html> 

, 비 욕심 정규식 귀하의 예를 들어 작동합니다 :

>>> import re 
>>> text = """<A href="#106">Item&nbsp;2. <B>Item&nbsp;2. Properties</B> this is an example this is an example""" 
>>> m = re.match(".*?Item&nbsp;2\.", text) 
>>> m.group(0) 
'<A href="#106">Item&nbsp;2.' 
관련 문제