##language:zh #pragma section-numbers off ##含有章节索引导航的 ZPyUG 文章通用模板 <> ## 默许导航,请保留 <> = txt 2 html = ##startInc == 题面 == {{{ free won reply-to python-cn@googlegroups.com to python-cn@googlegroups.com date Fri, Jul 11, 2008 at 19:12 subject [CPyUG:58809] 文本转换html问题 }}} 最近在完成一个 类似论坛的站点。by django. 出现了一个问题就是在回帖的时候,把回帖的内容转换成html格式发布出来。 目前尝试了些正则方式,都不太理想。 希望有经验的朋友能给个方向。 == limodou == {{{#!python #coding=utf-8 import re import cgi re_string = re.compile(r'(?P[<&>])|(?P^[ \t]+)|(?P\r\n|\r|\n)|(?P(^|\s*)((http|ftp)://.*?))(\s|$)', re.S|re.M|re.I) def text2html(text, tabstop=4): def do_sub(m): c = m.groupdict() if c['htmlchars']: return cgi.escape(c['htmlchars']) if c['lineend']: return '
' elif c['space']: t = m.group().replace('\t', ' '*tabstop) t = t.replace(' ', ' ') return t elif c['space'] == '\t': return ' '*tabstop; else: url = m.group('protocal') if url.startswith(' '): prefix = ' ' url = url[1:] else: prefix = '' last = m.groups()[-1] if last in ['\n', '\r', '\r\n']: last = '
' return '%s%s%s' % (prefix, url, url, last) return re.sub(re_string, do_sub, text) if __name__ == '__main__': text=""" http://groups.google.com/group/python-cn/pending """ print text2html(text) }}} == yrh == `` 我原先做个一个,不过不是for django的,你看看吧: {{{#!python def htmlEncode(strings): strings = strings.replace("\'", "'") strings = strings.replace("\\", "\") strings = strings.replace("\.", ".") strings = strings.replace("\|", "|") #strings = strings.replace('
', '') strings = strings.replace(" ", " ") strings = strings.replace("<", "<") #大写的html标签全部被替换,小写的
标签不会被替换 strings = re.sub(re.compile('<(?P\/?)(?Pstrong|center|font|img |pre)'), '<\g\g', strings) strings = re.sub('\n', '\n
', strings) return strings }}} 这个函数是我自己写的一个论坛的函数,允许 小写的
标签,其他html标签一律转换为文本。 替换斜杠,英文单引号、句号,竖线的目的是因为某些数据库存储这些字符的时候会出错,具体哪些字符要替换,你参考数据库手册好了。 如果你要更多功能的,建议你参考论坛处理ubb标签的方式,你google一下好了(比如动网论坛,不过大部分是asp的,python的很少) ##endInc ---- '''反馈''' 创建 by -- ZoomQuiet [<>]