1. 程式人生 > >Python 字符串過濾

Python 字符串過濾

color tail code fin span 內容 import pre ram

需求:

str1 = "

"""<div class="m_wrap clearfix"><ul class="clearfix"><br/><br/><
br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><b
r/><br/><br/><br/><br/><br/><li class="li_1 clearfix"><spa
n class="pt_title S_txt2">公司:</span><span class="pt_detail"><a href="h
ttp://s.weibo.com/user/&work=%E6%89%AC%E5%B7%9E%E6%8A%A5%E4%B8%9A%E9%9B%86%E5%9B%A2&from=inf&wvr=5&loc=infjob" target="_blank">揚州報業集團</a><br/>
地區:江蘇 ,揚州<br/> </span></li></ul></div></div></div></div>"""

"

想把 這段字符串的標簽全部都去掉,比如去掉 </li>, </ul>, </div>.。只保留不帶<>的內容,但是要保留<br/>,

有什麽好的辦法嗎?使用正則可以實現這個工作:

# coding:utf-8
import re newline
= """<div class="m_wrap clearfix"><ul class="clearfix"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br
  /><br/><br/><br/><br/><br/><li class="li_1 clearfix"><span class="pt_title S_txt2">公司:</span><span class="pt_detail"><a
  href="http://s.weibo.com/user/&work=%E6%89%AC%E5%B7%9E%E6%8A%A5%E4%B8%9A%E9%9B%86%E5%9B%A2&from=inf&wvr=5&loc=infjob" target="_blank">
  揚州報業集團</a><br/> 地區:江蘇 ,揚州<br/> </span></li></ul></div></div></div></div>
"""

newline= newline.replace(<br/>,!!!###) re_comment = re.compile(<[^>]*>) newlines = re_comment.sub(‘‘, newline) newlines = newlines.replace(!!!###,<br/>).replace(<br/><br/>,<br/>).replace(<br/><br/>,<br/>)
print newlines

輸出結果是:

C:\Python27\python.exe F:/squid_frame/ZYXT__weibo/test.py
<br/>公司:揚州報業集團<br/> 地區:江蘇 ,揚州<br/> 

Process finished with exit code 0

Python 字符串過濾