【问题标题】:Shorten the url to domain name in a string in python 2.7在python 2.7中将url缩短为字符串中的域名
【发布时间】:2012-12-06 06:31:31
【问题描述】:

假设我有一个字符串 This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py

我想得到这样的东西 This is a good doll www.google.com

我在 python 中尝试了print re.sub(r'(http://|https://)',"",a)) 函数,但我只能从中删除http:// 部分。关于如何在 python 2.7 中实现这一点的任何想法

【问题讨论】:

  • 您可能想要添加您的正则表达式尝试
  • 使用urlparse库解析url并获取主机名。

标签: python regex python-2.7


【解决方案1】:
>>> import re
>>> s = 'This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py'
>>> re.sub(r'(?:https?://)([^/]+)(?:\S+)', r"\1", s)
'This is a good doll www.google.com'

【讨论】:

    【解决方案2】:

    如果你想使用正则表达式,那么你可以这样做:

    >>> import re
    >>> the_string = "This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py"
    >>> def replacement(match):
    ...     return match.group(2)
    ... 
    >>> re.sub(r"(http://|https://)(.*?)/\S+", replacement, the_string)
    'This is a good doll www.google.com'
    

    【讨论】:

      【解决方案3】:
      >>> string = "This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py"
      >>> print string.replace('http://', '').split('/')[0]
      This is a good doll www.google.com
      

      【讨论】:

      • 如果 URL 后面有任何文本,这将不起作用,例如试试string = "This is a good doll http://www.google.com/a/bs/jdd/etc/etc/a.py lorem ipsum"
      • 它应该首先将整个 url 与一个正则表达式匹配,并且只在 url 上执行此操作。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      相关资源
      最近更新 更多