2011-07-23 106 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這樣的東西,以確保你沒有取代任何元素中的東西。