日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python 正则表达式过滤文本中的html标签 源代码解析

發(fā)布時(shí)間:2023/12/13 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python 正则表达式过滤文本中的html标签 源代码解析 小編覺(jué)得挺不錯(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) #過(guò)濾腳本re_style = re.compile('<\s*style[^>]*>[^<]*<\s*/\s*style\s*>', re.I) #過(guò)濾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 匹配單詞的開(kāi)始或結(jié)束

^ 匹配字符串的開(kāi)始

$ 匹配字符串的結(jié)束

\W 匹配任意不是字母,數(shù)字,下劃線,漢字的字符

\S 匹配任意不是空白符的字符

\D 匹配任意非數(shù)字的字符

\B 匹配不是單詞開(kāi)頭或結(jié)束的位置

[^x] 匹配除了x以外的任意字符

[^aeiou] 匹配除了aeiou這幾個(gè)字母以外的任意字符


常用的限定符代碼/語(yǔ)法說(shuō)明:

*重復(fù)零次或更多次

+重復(fù)一次或更多次

?重復(fù)零次或一次

{n}重復(fù)n次

{n,}重復(fù)n次或更多次

{n,m}重復(fù)n到m次


關(guān)于命名組:

命名組:(?P<name>.....),詳見(jiàn):http://scm002.iteye.com/blog/1491521

這篇文章里面還提到了界定( 問(wèn)號(hào)開(kāi)頭,前向則有個(gè)'<'號(hào),非則有個(gè)'!' 號(hào) ):

前向界定?(?<=…)

后向界定?(?=…) ?

前向非界定 (?<!....)

后向非界定 (?!.....)





轉(zhuǎn)載于:https://www.cnblogs.com/rav009/p/5131106.html

總結(jié)

以上是生活随笔為你收集整理的python 正则表达式过滤文本中的html标签 源代码解析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。