python实现html转ubb代码(html2ubb)

yipeiwu_com6年前Python基础

这两天在用python写一个采集器,有个功能模块是html代码转换为ubb,网上貌似没有现成程序,就自己写了个函数,顺便锻炼下自己的正则。

import re
def Html2UBB(content):
	#以下是将html标签转为ubb标签
	pattern = re.compile( '<a href=\"([sS]+?)\"[^>]*>([sS]+?)</a>',re.I)
	content = pattern.sub(r'[url=1]2[/url]',content)
	pattern = re.compile( '<img[^>]+src=\"([^\"]+)\"[^>]*>',re.I)
	content = pattern.sub(r'[img]1[/img]',content)
	pattern = re.compile( '<strong>([sS]+?)</strong>',re.I)
	content = pattern.sub(r'[b]1[/b]',content)
	pattern = re.compile( '<font color=\"([sS]+?)\">([sS]+?)</font>',re.I)
	content = pattern.sub(r'[1]2[/1]',content)
	pattern = re.compile( '<[^>]*?>',re.I)
	content = pattern.sub('',content)
	#以下是将html转义字符转为普通字符
	content = content.replace('<','<')
	content = content.replace('>','>')
	content = content.replace('”','”')
	content = content.replace('“','“')
	content = content.replace('"','"')
	content = content.replace('©','©')
	content = content.replace('®','®')
	content = content.replace(' ',' ')
	content = content.replace('—','—')
	content = content.replace('–','–')
	content = content.replace('‹','‹')
	content = content.replace('›','›')
	content = content.replace('…','…')
	content = content.replace('&','&')
	return content

使用时直接调用Html2UBB函数,返回值就是ubb码了html转ubb

相关文章

浅谈python中截取字符函数strip,lstrip,rstrip

浅谈python中截取字符函数strip,lstrip,rstrip

一、起因 今天在做角色控制中,有一个地方用到rstrip,判断用户请求的url是否与数据库对应可用权限中url相符。 if request.path == x.url or reques...

Python+numpy实现矩阵的行列扩展方式

Python+numpy实现矩阵的行列扩展方式

对于numpy矩阵,行列扩展有三种比较常用的方法: 1、使用矩阵对象的c_方法扩展列,使用矩阵对象的r_方法扩展行。 2、使用numpy扩展库提供的insert()函数,使用axis参数...

Python使用指定端口进行http请求的例子

使用requests库 class SourcePortAdapter(HTTPAdapter): """"Transport adapter" that allows us to...

Python中的rjust()方法使用详解

 rjust()该方法返回字符串合理字符串的右边的长度宽度。填充是通过使用指定的fillchar(默认为空格)。如果宽度小于len(s)返回原始字符串。 语法 以下是rjust...

python创建列表和向列表添加元素的实现方法

今天的学习内容是python中的列表的相关内容。 一.创建列表 1.创建一个普通列表 >>> tabulation1 = ['大圣','天蓬','卷帘'] >...