开发者

Python: Keyword to Links

I am building a blog on Google App Engine. I would like to convert some keywords in my blog posts to links, just like what you see in many WordPress blogs.

Here is one WP plugin which do the same thing:http://wordpress.org/extend/plugins/blog-mechanics-keyword-link-plugin-v01/

A plugin that allows you to define keyword/link pairs. The keywords are automatically linked in each of your posts.

I think this is more than a simple Python Replace. What I am dealing with is HTML code. It can be quite complex sometimes.

Take the following code snippet as an example. I want to conver the word example into a link to http://example.com:

Here is an example link:<a href="http://example.com">example.com</a>

By a simple Python replace function which replaces example with <a href="http://example.com">example</a>, it would output:

Here is an <a href="http://example.com">example</a> link:<开发者_如何转开发a href="http://<a href="http://example.com">example</a>.com"><a href="http://example.com">example</a>.com</a>

but I want:

Here is an <a href="http://example.com">example</a> link:<a href="http://example.com">example.com</a>

Is there any Python plugin that capable of this? Thanks a lot!


This is roughly what you could do using Beautifulsoup:

from BeautifulSoup import BeautifulSoup

html_body ="""
Here is an example link:<a href='http://example.com'>example.com</a>
"""
soup = BeautifulSoup(html_body)
for link_tag in soup.findAll('a'):
    link_tag.string = "%s%s%s" % ('|',link_tag.string,'|')
for text in soup.findAll(text=True):
    text_formatted = ['<a href=""http://example.com"">example</a>'\ 
    if word == 'example' and not (word.startswith('|') and word.endswith('|'))\
    else word for word in foo.split() ]
    text.replaceWith(' '.join(text_formatted))
for link_tag in soup.findAll('a'):
    link_tag.string = link_tag.string[1:-1]
print soup

Basically I'm stripping out all the text from the post_body, replacing the example word with the given link, without touching the links text that are saved by the '|' characters during the parsing.

This is not 100% perfect, for example it does not work if the word you are trying to replace ends with a period; with some patience you could fix all the edge cases.


This would probably be better suited to client-side code. You could easily modify a word highlighter to get the desired results. By keeping this client-side, you can avoid having to expire page caches when your 'tags' change.

If you really need it to be processed server-side, then you need to look at using re.sub which lets you pass in a function, but unless you are operating on plain-text you will have to first parse the HTML using something like minidom to ensure you are not replacing something in the middle of any elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜