【问题标题】:Python: replace urls with title names from a stringPython:用字符串中的标题名称替换网址
【发布时间】:2011-02-17 04:59:35
【问题描述】:

我想从字符串中删除 url 并将其替换为原始内容的标题。

例如:

mystring = "Ah I like this site: http://www.stackoverflow.com. Also I must say I like http://www.digg.com"

sanitize(mystring) # it becomes "Ah I like this site: Stack Overflow. Also I must say I like Digg - The Latest News Headlines, Videos and Images"

为了用标题替换url,我写了这个snipplet:

#get_title: string -> string
def get_title(url):
    """Returns the title of the input URL"""

    output = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
    return output.title.string

不知何故,我需要将此函数应用于捕获 url 并通过 get_title 转换为标题的字符串。

【问题讨论】:

  • 我已经更新了问题,对不起:)

标签: python url replace title


【解决方案1】:

这是一个关于在 Python 中验证 url 的信息的问题:How do you validate a URL with a regular expression in Python?

urlparse 模块可能是你最好的选择。您仍然需要决定在您的应用程序上下文中构成有效 url 的内容。

要检查字符串中的 url,您需要遍历字符串中的每个单词,检查它,然后用标题替换有效的 url。

示例代码(您需要编写 valid_url):

def sanitize(mystring):
  for word in mystring.split(" "):
    if valid_url(word):
      mystring = mystring.replace(word, get_title(word))
  return mystring

【讨论】:

    【解决方案2】:

    您可能可以使用正则表达式和替换来解决这个问题(re.sub 接受一个函数,该函数将为每次出现的匹配对象传递并返回替换它的字符串):

    url = re.compile("http:\/\/(.*?)/")
    text = url.sub(get_title, text)
    

    困难的是创建一个匹配 URL 的正则表达式,而不是更多,而不是更少。

    【讨论】:

    • 1. get_title() 应该接受 MatchObject(不仅仅是字符串)。 2. Django 使用类似 r'https?://[^ \t\n\r]+' 的方式来链接文本
    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2020-11-06
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-30
    • 2020-10-21
    相关资源
    最近更新 更多