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生成短uuid的方法实例详解

python的uuid都是32位的,比较长,处理起来效率比较低, 本算法利用62个可打印字符,通过随机生成32位UUID,由于UUID都为十六进制,所以将UUID分成8组,每4个为一组,...

python访问类中docstring注释的实现方法

本文实例讲述了python访问类中docstring注释的实现方法。分享给大家供大家参考。具体分析如下: python的类注释是可以通过代码访问的,这样非常利于书写说明文档 clas...

python里使用正则的findall函数的实例详解

python里使用正则的findall函数的实例详解 在前面学习了正则的search()函数,这个函数可以找到一个匹配的字符串返回,但是想找到所有匹配的字符串返回,怎么办呢?其实得使用f...

基于python实现自动化办公学习笔记(CSV、word、Excel、PPT)

1、CSV (1)写csv文件 import csv def writecsv(path,data): with open(path, "w") as f: wri...

python 字典(dict)遍历的四种方法性能测试报告

python中,遍历dict的方法有四种。但这四种遍历的性能如何呢?我做了如下的测试 l = [(x,x) for x in xrange(10000)] d = dict(l)...