我正在寻找一个独立的python函数,它将接收一个字符串并返回一个字符串,其中包含转换为链接的电子邮件地址。
示例:
>>>s = 'blah blah blah a@at.com blah blah blah'
>>>link(s)
'blah blah blah <a href="mailto:a@at.com">a@at.com</a> blah blah blah'
答案 0 :(得分:8)
这样的东西?
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("\w+@(?:\w|\.)+", anchor_from_email_address_match, text)
print replace_email_addresses_with_anchors(
"An address: bob@example.com, and another: joe@example.com")
答案 1 :(得分:2)
>>> 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 a@at.com blah blah blah'
>>> convert_emails(s)
'blah blah blah <a href="mailto:a@at.com">a@at.com</a> blah blah blah'
>>>
不是非常强大,但适用于非常基本的情况。
答案 2 :(得分:1)
def link(s):
return '<a href="mailto:{0}">{0}</a>'.format(s)