【问题标题】:Python: Convert email address to HTML linkPython:将电子邮件地址转换为 HTML 链接
【发布时间】:2011-08-11 06:59:27
【问题描述】:

我正在寻找一个独立的 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'

【问题讨论】:

标签: python html regex string email-validation


【解决方案1】:

这样的?

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")

【讨论】:

  • 您误读了:xml 模块仅用于 HTML 引用。正则表达式用于查找电子邮件地址。我搞砸了我的字符串格式 - 已修复。
  • 哦哦。是的,我看错了。无论如何都运作良好。然后为 HTML 引用 +1:D
  • 这不会捕获 yahoo-inc.com 等域中的“-”字符。您可以通过修改 replace_email_addresses_with_anchors 添加这些:return re.sub("\w+@(?:\w|\.|\-)+", anchor_from_email_address_match, text)
  • 不会在我的工作中工作,因为每个人都有 first.surname@company.com 形式的电子邮件地址,所以我建议将 re 修改为 "(?:\w|\.|\- )+@(?:\w|\.|\-)+"
【解决方案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'
>>> 

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

【讨论】:

  • 请注意,这里的 DTing 不会打扰 HTML 引用。您应该使用 HTML 引用,除非您控制输入并且知道其中不可能包含具有特殊含义的字符。原因可以搜索“XSS”或“代码注入”,但this famous cartoon 说得更好。
  • +1 因为它很简单。对于我的用例,这很好,我只是从需求文档转换文本,而不是来自潜在的恶意用户。
【解决方案3】:
def link(s):
    return '<a href="mailto:{0}">{0}</a>'.format(s)

【讨论】:

  • 这假设您已经匹配并传递了电子邮件地址。
猜你喜欢
  • 1970-01-01
  • 2019-07-17
  • 2023-03-18
  • 2013-02-04
  • 2011-03-12
  • 1970-01-01
  • 2013-08-03
  • 1970-01-01
相关资源
最近更新 更多