python文本筛选html_python 正则表达式过滤文本中的html标签 源代码解析
#py2.7
#coding:utf-8
import re
import os
import chardet
def filter_tag(htmlstr):
re_cdata = re.compile('^>]*>', re.I)
re_script = re.compile(']*>[^', re.I) #過濾腳本
re_style = re.compile(']*>[^', re.I) #過濾style
re_br = re.compile('
')
re_h = re.compile('?\w+[^>]*>')
re_comment = re.compile('')
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
def replaceCharEntity(htmlstr):
CHAR_ENTITIES={'nbsp':'','160':'',
'lt':'
'gt':'>','62':'>',
'amp':'&','38':'&',
'quot':'"','34':'"'}
re_charEntity=re.compile(r'?(?P\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
if __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 txtname
f=open(root+os.path.sep+txtname,'w')
f.write(rs.encode('utf-8'))
f.close()
總結:
轉義符:
. 匹配除換行符以外的任意字符
\w 匹配字母或數字或下劃線或漢字
\s 匹配任意的空白符
\d 匹配數字
\b 匹配單詞的開始或結束
^ 匹配字符串的開始
$ 匹配字符串的結束
\W 匹配任意不是字母,數字,下劃線,漢字的字符
\S 匹配任意不是空白符的字符
\D 匹配任意非數字的字符
\B 匹配不是單詞開頭或結束的位置
[^x] 匹配除了x以外的任意字符
[^aeiou] 匹配除了aeiou這幾個字母以外的任意字符
常用的限定符代碼/語法說明:
*重復零次或更多次
+重復一次或更多次
?重復零次或一次
{n}重復n次
{n,}重復n次或更多次
{n,m}重復n到m次
關于命名組:
這篇文章里面還提到了界定( 問號開頭,前向則有個'
前向界定?(?<=…)
后向界定(?=…)
前向非界定 (?
后向非界定 (?!.....)
總結
以上是生活随笔為你收集整理的python文本筛选html_python 正则表达式过滤文本中的html标签 源代码解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python课程设计矩阵对角线之和_在p
- 下一篇: ubuntu安装python3.6_Ub