Python 字符串过滤

需求:

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:Python27python.exe F:/squid_frame/ZYXT__weibo/test.py
<br/>公司:扬州报业集团<br/> 地区:江苏 ,扬州<br/> 

Process finished with exit code 0
原文地址:https://www.cnblogs.com/xuchunlin/p/9599315.html