Home >Backend Development >Python Tutorial >python实现html转ubb代码(html2ubb)

python实现html转ubb代码(html2ubb)

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-06-16 08:43:301330browse

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

import re
def Html2UBB(content):
	#以下是将html标签转为ubb标签
	pattern = re.compile( '<a href=\"([sS]+&#63;)\"[^>]*>([sS]+&#63;)</a>',re.I)
	content = pattern.sub(r'[url=1]2[/url]',content)
	pattern = re.compile( '<img [^ alt="python实现html转ubb代码(html2ubb)" >]+src=\"([^\"]+)\"[^>]*>',re.I)
	content = pattern.sub(r'[img]1[/img]',content)
	pattern = re.compile( '<strong>([sS]+&#63;)</strong>',re.I)
	content = pattern.sub(r'[b]1[/b]',content)
	pattern = re.compile( '<font color=\"([sS]+&#63;)\">([sS]+&#63;)</font>',re.I)
	content = pattern.sub(r'[1]2[/1]',content)
	pattern = re.compile( '<[^>]*&#63;>',re.I)
	content = pattern.sub('',content)
	#以下是将html转义字符转为普通字符
	content = content.replace('<','<')
	content = content.replace('>','>')
	content = content.replace('&rdquo;','”')
	content = content.replace('&ldquo;','“')
	content = content.replace('"','"')
	content = content.replace('&copy;','&copy;')
	content = content.replace('&reg;','&reg;')
	content = content.replace(' ',' ')
	content = content.replace('&mdash;','—')
	content = content.replace('&ndash;','–')
	content = content.replace('&lsaquo;','&#8249;')
	content = content.replace('&rsaquo;','&#8250;')
	content = content.replace('&hellip;','…')
	content = content.replace('&','&')
	return content

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn