2010-05-08 34 views
3

我想从字符串中删除网址,并将它们替换为原始内容的标题。Python:用字符串中的标题名称替换网址

例如:

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" 

对于标题取代网址,我写了这个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 

不知何故,我需要这个功能适用于字符串在那里抓到的网址和转换通过get_title标题。

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

的:

+1

和你的问题是什么? – msw 2010-05-08 17:28:25

+0

我已经更新了这个问题,对不起:) – Hellnar 2010-05-08 17:30:06

回答

3

这里是信息的问题在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的正则表达式,而不是更多,而不是更少。

+0

1.'get_title()'应该接受MatchObject(不只是字符串)。 2. Django使用一些像r'https的思想?:// [^ \ t \ n \ r] +'来链接文本 – jfs 2010-05-08 18:33:09