python過濾去除html標籤 提取純文字

2021-10-08 19:31:09 字數 2528 閱讀 1421

python正則過濾html標籤,提取純文字

上**

def

filterhtmltag

(htmlstr)

:'''

過濾html中的標籤

'''#相容換行

s = htmlstr.replace(

'\r\n'

,'\n'

) s = htmlstr.replace(

'\r'

,'\n'

)#規則

re_cdata = re.

compile

('//]*//\]\]>'

,re.i)

#匹配cdata

re_script = re.

compile

('<\s*script[^>]*>[\s\s]*?<\s*/\s*script\s*>'

,re.i)

#script

re_style = re.

compile

('<\s*style[^>]*>[\s\s]*?<\s*/\s*style\s*>'

,re.i)

#style

re_br = re.

compile('

',re.i)

#br標籤換行

re_p = re.

compile

('<\/p>'

,re.i)

#p標籤換行

re_h = re.

compile

('<[\!|/]?\w+[^>]*>'

,re.i)

#html標籤

re_comment = re.

compile(''

)#html注釋

re_hendstr = re.

compile

('^\s*|\s*$'

)#頭尾空白字元

re_lineblank = re.

compile

('[\t\f\v ]*'

)#空白字元

re_linenum = re.

compile

('\n+'

)#連續換行保留1個

#處理 s = re_cdata.sub(

'',s)

#去cdata

s = re_script.sub(

'',s)

#去script

s = re_style.sub(

'',s)

#去style

s = re_br.sub(

'\n'

,s)#br標籤換行

s = re_p.sub(

'\n'

,s)#p標籤換行

s = re_h.sub(

'',s)

#去html標籤

s = re_comment.sub(

'',s)

#去html注釋

s = re_lineblank.sub(

'',s)

#去空白字元

s = re_linenum.sub(

'\n'

,s)#連續換行保留1個

s = re_hendstr.sub(

'',s)

#去頭尾空白字元

#替換實體

s = replacecharentity(s)

return s

defreplacecharentity

(htmlstr)

:'''

替換html中常用的字元實體

使用正常的字元替換html中特殊的字元實體

可以新增新的字元實體到char_entities 中

char_entities是乙個字典前面是特殊字元實體 後面是其對應的正常字元

:param htmlstr:

'''self.htmlstr = htmlstr

char_entities=

re_charentity=re.

compile

(r'&#?(?p\w+);'

) sz=re_charentity.search(htmlstr)

while sz:

entity=sz.group(

)#entity全稱,如》

key=sz.group(

'name'

)#去除&;後的字元如(" "--->key = "nbsp") 去除&;後entity,如》為gt

try:

htmlstr= re_charentity.sub(char_entities[key]

,htmlstr,1)

sz=re_charentity.search(htmlstr)

except keyerror:

#以空串代替

htmlstr=re_charentity.sub(

'',htmlstr,1)

sz=re_charentity.search(htmlstr)

return htmlstr

sql去除html標籤

分類 sql舉報 sql資料庫sql函式 1 建立函式 sql view plain copy create function dbo clearhtml maco varchar 8000 returns varchar 8000 as begin declare i int while 1 1 ...

php 只提取文字,去除html標籤樣式和轉義字元

只提取文字,去除html標籤樣式和轉義字元。主要用於提取富文字編輯的內容。把html實體標籤轉換為字元 html string htmlspecialchars decode content 將空格替換成空 content str replace html string 函式剝去字串中的 html ...

python去除所有html標籤的方法

這段 可以用於去除文字裡的字串標籤,不包括標籤裡面的內容 import re 程式設計客棧html 程式設計客棧a 程式設計客棧href 我們,python學習!dr re.fezczocmclcompile r re.s dd dr.sub html print dd 執行結果如下 我們,pyth...