Python:将电子邮件地址转换为HTML链接

问题描述:

我正在寻找一种独立的Python函数,它将接收一个字符串并返回一个字符串,并将电子邮件地址转换为链接。Python:将电子邮件地址转换为HTML链接

例子:

>>>s = 'blah blah blah [email protected] blah blah blah' 
>>>link(s) 
'blah blah blah <a href="mailto:[email protected]">[email protected]</a> blah blah blah' 
+0

到目前为止你有什么/尝试过? – Santa 2011-04-23 00:02:36

+0

@Santa:我尝试了http://labs.kortina.net/2009/08/14/auto-link-plain-text-urls-in-python/的代码,但没有奏效。 – Muhd 2011-04-23 00:45:37

像这样的事情?

import re 
import xml.sax.saxutils 

def anchor_from_email_address_match(match): 
    address = match.group(0) 
    return "<a href=%s>%s</a>" % (
     xml.sax.saxutils.quoteattr("mailto:" + address), 
     xml.sax.saxutils.escape(address)) 

def replace_email_addresses_with_anchors(text): 
    return re.sub("\[email protected](?:\w|\.)+", anchor_from_email_address_match, text) 

print replace_email_addresses_with_anchors(
    "An address: [email protected], and another: [email protected]") 
+0

你误读了:xml模块仅用于HTML引用。正则表达式用于查找电子邮件地址。我搞砸了我的字符串格式 - 修复。 – 2011-04-23 00:14:39

+0

呃哦。是的,我误解了它。无论工作得好。 +1用于HTML引用然后:D为 – 2011-04-23 00:20:09

+0

+1为漫画,并且html引用太... – DTing 2011-04-23 00:29:03

def link(s): 
    return '<a href="mailto:{0}">{0}</a>'.format(s) 
+0

这假设你已经匹配了电子邮件地址并通过了它。 – jathanism 2011-04-23 00:01:21

>>> def convert_emails(s): 
...  words = [ word if '@' not in word else '<a href="mailto:{0}">{0}</a>'.format(word) for word in s.split(" ") ] 
...  return " ".join(words) 
... 
>>> s = 'blah blah blah [email protected] blah blah blah' 
>>> convert_emails(s) 
'blah blah blah <a href="mailto:[email protected]">[email protected]</a> blah blah blah' 
>>> 

不是超级强大的,但适用于非常基本的情况。

+1

注意DTing并不打扰HTML引用。除非你控制输入,并且知道它不可能包含具有特殊含义的字符,否则应该使用HTML引号。你可以搜索“XSS”或“代码注入”,但[这个着名的漫画](http://xkcd.com/327/)说得更好。 – 2011-04-23 00:24:17

+0

+1因为它很简单。对于我的用例来说,这很好,我只是从需求文档转换文本,而不是从潜在的恶意用户转换文本。 – Muhd 2011-04-23 00:51:09