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

发布于 2024-11-03 02:58:13 字数 590 浏览 0 评论 0原文

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

例子:

>>>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'

I'm looking for a stand-alone python function that will take in a string and return a string with the email addresses converted to links.

Example:

>>>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'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

满栀 2024-11-10 02:58:13

像这样的东西吗?

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: [email protected], and another: [email protected]")

Something like this?

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: [email protected], and another: [email protected]")
浅笑依然 2024-11-10 02:58:13
>>> 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'
>>> 

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

>>> 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'
>>> 

Not super robust but works for very basic cases.

不必在意 2024-11-10 02:58:13
def link(s):
    return '<a href="mailto:{0}">{0}</a>'.format(s)
def link(s):
    return '<a href="mailto:{0}">{0}</a>'.format(s)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文