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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

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

發布時間:2025/3/15 python 13 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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标签 源代码解析的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。