Python之使用正则函数处理文本里的杂质

# -*- coding: utf-8 -*-
import re


class Tool():
# 去除img标签,7位长空格
removeImg = re.compile('<img.*?>| {7}|')
# 删除span标签
removeSpan = re.compile('<span.*?>| {7}|')
# 删除超链接标签
removeAddr = re.compile('<a.*?>|</a>')
# 把换行的标签换为\n
replaceLine = re.compile('<tr>|<div>|</div>|</p>')
# 将表格制表<td>替换为\t
replaceTD = re.compile('<td>')
# 把段落开头换为\n加空两格
replacePara = re.compile('<p.*?>')
# 将换行符或双换行符替换为\n
replaceBR = re.compile('<br><br>|<br>')
# 将其余标签剔除
removeExtraTag = re.compile('<.*?>')

def replace(self, content):
content = re.sub(self.removeImg, "", content)
content = re.sub(self.removeSpan, "", content)
content = re.sub(self.removeAddr, "", content)
content = re.sub(self.replaceLine, "\n", content)
content = re.sub(self.replaceTD, "\t", content)
content = re.sub(self.replacePara, "\n ", content)
content = re.sub(self.replaceBR, "\n", content)
content = re.sub(self.removeExtraTag, "", content)
# strip()将前后多余内容删除
return content.strip()
posted @ 2017-09-17 18:07  诡道!!!  阅读(380)  评论(0编辑  收藏  举报