Python字符串替换:关键字到URL

时间:2012-06-09 10:55:38

标签: python string google-app-engine utf-8

我打算用字符串中的url替换一些关键字,例如

content.replace("Google","<a href="http://www.google.com">Google</a>")

但是,我只想用url替换关键字,如果还没有包含在url中那么。

内容很简单:

<p><b>This is an example!</b></p><p>I love <a href="http://www.google.com">Google</a></p><p><a href="http://www.google.com"><img src="/google.jpg" /></a></p>

主要是<a><img>代码。

主要问题:如何确定关键字是否已包含在<a><img>代码中?

以下是PHP find and replace keywords with urls ONLY if not already wrapped in a url中的类似问题,但答案并非有效。

Python中有更好的解决方案吗?更好的代码示例。谢谢!

3 个答案:

答案 0 :(得分:4)

我使用Beatiful Soup来解析我的HTML,因为带有正则表达式的parsing HTML可以证明是棘手的。如果你使用美丽的汤,你可以玩previous_sibling和previous_element找出你需要的东西。

您以这种方式进行互动:

soup.find_all('img')

答案 1 :(得分:3)

正如Chris-Top所说,BeautifulSoup是要走的路:

from BeautifulSoup import BeautifulSoup, Tag, NavigableString
import re    

html = """
<div>
    <p>The quick brown <a href='http://en.wikipedia.org/wiki/Dog'>fox</a> jumped over the lazy Dog</p>
    <p>The <a href='http://en.wikipedia.org/wiki/Dog'>dog</a>, who was, in reality, not so lazy, gave chase to the fox.</p>
    <p>See image for reference:</p>
    <img src='dog_chasing_fox.jpg' title='Dog chasing fox'/>
</div>
"""
soup = BeautifulSoup(html)

#search term, url reference
keywords = [("dog","http://en.wikipedia.org/wiki/Dog"),
            ("fox","http://en.wikipedia.org/wiki/Fox")]

def insertLinks(string_value,string_href):
    for t in soup.findAll(text=re.compile(string_value, re.IGNORECASE)):
            if t.parent.name !='a':
                    a = Tag('a', name='a')
                    a['href'] = string_href
                    a.insert(0, NavigableString(string_value))
                    string_list = re.compile(string_value, re.IGNORECASE).split(t)
                    replacement_text = soup.new_string(string_list[0])
                    t.replace_with(replacement_text)
                    replacement_text.insert_after(a)
                    a.insert_after(soup.new_string(string_list[1]))


for word in keywords:
    insertLinks(word[0],word[1])

print soup

将屈服:

<div>
    <p>The quick brown <a href="http://en.wikipedia.org/wiki/Dog">fox</a> jumped over the lazy <a href="http://en.wikipedia.org/wiki/Dog">dog</a></p>
    <p>The <a href="http://en.wikipedia.org/wiki/Dog">dog</a>, who was, in reality, not so lazy, gave chase to the <a href="http://en.wikipedia.org/wiki/Fox">fox</a>.</p>
    <p>See image for reference:</p>
    <img src="dog_chasing_fox.jpg" title="Dog chasing fox"/>
</div>

答案 2 :(得分:0)

您可以尝试添加前一篇文章中提到的正则表达式。首先根据正则表达式检查字符串,以检查它是否已包装在URL中。这应该很简单,因为对re库的简单调用及其search()方法应该可以解决问题。

如果您需要特定的正则表达式和搜索方法,这是一个很好的教程:http://www.tutorialspoint.com/python/python_reg_expressions.htm

检查字符串后是否已将其包装在URL中,如果尚未包含在URL中,则可以调用replace函数。

这是我写的一个简单示例:

    import re

    x = "<a href=""http://www.google.com"">Google</a>"
    y = 'Google'

    def checkURL(string):
        if re.search(r'<a href.+', string):
            print "URL Wrapped Already"
            print string
        else:
            string = string.replace('Google', "<a href=""http://www.google.com"">Google</a>")
            print "URL Not Wrapped:"
            print string

    checkURL(x)
    checkURL(y)

我希望这能回答你的问题!