2011-07-23 63 views
1

我正在Google App Engine上构建一个博客。我想将我的博文中的一些关键字转换为链接,就像您在许多WordPress博客中看到的一样。Python:链接关键字

这里是一个WP插件,做同样的事情:http://wordpress.org/extend/plugins/blog-mechanics-keyword-link-plugin-v01/

一个插件,允许你定义关键字/链接对。关键字会自动链接到您的每个帖子中。

我认为这不仅仅是一个简单的Python替换。我正在处理的是HTML代码。有时可能会非常复杂。

以下面的代码片段为例。我想这个词example CONVER到链接到http://example.com

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

通过一个简单的Python替换功能将取代example<a href="http://example.com">example</a>,它会输出:

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> 

,但我想:

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

是否有任何Python插件能够做到这一点?非常感谢!

+1

“一个简单的Python替换函数” - 向我们展示您的代码。 –

+0

@罗曼呃,'my_string.replace(...)'? –

回答

1

这大约是你可以做什么用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 

基本上我从post_body剥离出来的所有文字,与给定链路代替实施例词,而不触及链接文本是由'|'保存解析期间的字符。

这不是100%完美的,例如,如果您尝试更换的词以句点结尾,则它不起作用;有一些耐心,你可以修复所有的边缘情况。

+0

谢谢。 AFAIK,BeautifulSoup不仅速度缓慢,而且还扼杀格式错误的HTML。但感谢提示。 – DocWiki

+0

@Doc它很慢,但由于您处于Google App Engine等受限环境中,因此您不得不纯粹采用Python中的某些内容。没有这个限制,lxml是首选的库。 – systempuntoout

+0

eeeeeeeew。 (@使用|符号来分隔链接)。 –

1

这可能会更适合客户端代码。您可以轻松修改word highlighter以获得理想的结果。通过保持这个客户端,你可以避免当你的'标签'变化时不得不失效页面缓存。

如果你真的需要它来处理服务器端,那么你需要看看使用re.sub它可以让你传入一个函数,但除非你在纯文本上操作,你将不得不首先解析HTML像minidom这样的东西,以确保你没有取代任何元素中的东西。