python 正则表达式过滤文本中的html标签 源代码解析
生活随笔
收集整理的這篇文章主要介紹了
python 正则表达式过滤文本中的html标签 源代码解析
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
#py2.7
#coding:utf-8import re
import os
import chardetdef 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) #過濾stylere_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 sdef replaceCharEntity(htmlstr):CHAR_ENTITIES={'nbsp':'','160':'','lt':'<','60':'<','gt':'>','62':'>','amp':'&','38':'&','quot':'"','34':'"'}re_charEntity=re.compile(r'&#?(?P<name>\w+);') #命名組,把 匹配字段中\(zhòng)w+的部分命名為name,可以用group函數(shù)獲取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表示替換第一個(gè)匹配sz=re_charEntity.search(htmlstr)except KeyError:htmlstr=re_charEntity.sub('',htmlstr,1)sz=re_charEntity.search(htmlstr)return htmlstrif __name__=='__main__':cpath=os.getcwd()for root,dirs,files in os.walk(cpath):for file in files:if file.endswith('htm') or file.endswith('html'):f=open(root+os.path.sep+file)stream=f.read()htmlstr =stream.decode(chardet.detect(stream)['encoding'])rs=filter_tag(htmlstr)f.close()txtname=re.sub(r'.htm*$','.txt',file)print txtnamef=open(root+os.path.sep+txtname,'w')f.write(rs.encode('utf-8'))f.close()
總結(jié):
轉(zhuǎn)義符:
. 匹配除換行符以外的任意字符
\w 匹配字母或數(shù)字或下劃線或漢字
\s 匹配任意的空白符
\d 匹配數(shù)字
\b 匹配單詞的開始或結(jié)束
^ 匹配字符串的開始
$ 匹配字符串的結(jié)束
\W 匹配任意不是字母,數(shù)字,下劃線,漢字的字符
\S 匹配任意不是空白符的字符
\D 匹配任意非數(shù)字的字符
\B 匹配不是單詞開頭或結(jié)束的位置
[^x] 匹配除了x以外的任意字符
[^aeiou] 匹配除了aeiou這幾個(gè)字母以外的任意字符
常用的限定符代碼/語法說明:
*重復(fù)零次或更多次
+重復(fù)一次或更多次
?重復(fù)零次或一次
{n}重復(fù)n次
{n,}重復(fù)n次或更多次
{n,m}重復(fù)n到m次
關(guān)于命名組:
命名組:(?P<name>.....),詳見:http://scm002.iteye.com/blog/1491521這篇文章里面還提到了界定( 問號開頭,前向則有個(gè)'<'號,非則有個(gè)'!' 號 ):
前向界定?(?<=…)
后向界定?(?=…) ?
前向非界定 (?<!....)
后向非界定 (?!.....)
轉(zhuǎn)載于:https://www.cnblogs.com/rav009/p/5131106.html
總結(jié)
以上是生活随笔為你收集整理的python 正则表达式过滤文本中的html标签 源代码解析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RTX 4080未出生就被砍一刀!核心缩
- 下一篇: 北京银行小白卡年费多少?如何减免?