1. 程式人生 > >python 過濾文字中的HTML標籤

python 過濾文字中的HTML標籤

'''過濾HTML中的標籤 #將HTML中標籤等資訊去掉 #@param htmlstr HTML字串.''' def filter_tag(htmlstr):       re_cdata = re.compile('<!DOCTYPE HTML PUBLIC[^>]*>', re.I)       re_script = re.compile('<\s*script[^>]*>[^<]*<\s*/\s*script\s*>', re.I) #過濾指令碼       re_style = re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>', re.I) #過濾style       re_br = re.compile('<br\s*?/?>')       re_h = re.compile('</?\w+[^>]*>')       re_comment = re.compile('<!--[\s\S]*-->')       s = re_cdata.sub('', htmlstr)       s = re_script.sub('', s)       s=re_style.sub('',s)       s=re_br.sub('\n',s)       s=re_h.sub(' ',s)       s=re_comment.sub('',s)       blank_line=re.compile('\n+')       s=blank_line.sub('\n',s)       s=re.sub('\s+',' ',s)       s=replaceCharEntity(s)       return s   '''##替換常用HTML字元實體. #使用正常的字元替換HTML中特殊的字元實體. #你可以新增新的實體字元到CHAR_ENTITIES中,處理更多HTML字元實體. #@param htmlstr HTML字串.''' def replaceCharEntity(htmlstr):       CHAR_ENTITIES={'nbsp':'','160':'',                       'lt':'<','60':'<',                       'gt':'>','62':'>',                       'amp':'&','38':'&',                       'quot':'"''"','34':'"'}       re_charEntity=re.compile(r'&#?(?P<name>\w+);') #命名組,把 匹配欄位中\w+的部分命名為name,可以用group函式獲取       sz=re_charEntity.search(htmlstr)       while sz:           #entity=sz.group()           key=sz.group('name') #命名組的獲取           try:               htmlstr=re_charEntity.sub(CHAR_ENTITIES[key],htmlstr,1) #1表示替換第一個匹配               sz=re_charEntity.search(htmlstr)           except KeyError:               htmlstr=re_charEntity.sub('',htmlstr,1)               sz=re_charEntity.search(htmlstr)       return htmlstr