2015-08-18 36 views
1

我在某個網站上有內容,其中某些關鍵字和關鍵字應該鏈接到其他內容。我不想手動將鏈接插入到內容中。在Python中執行此操作的最佳方式是什麼,最好不使用任何DOM庫?將HTML中的短語轉換爲與Python的鏈接

例如,我有這樣的文字:

...And this can be accomplished with the Awesome Method. Blah blah blah....

Key-phrase: awesome method

這是所需的輸出:

...And this can be accomplished with the <a href="/path/to/awesome-method">Awesome Method</a>. Blah blah blah....

我有這樣的關鍵詞和所述列表相應的URL。短語可以在任何情況下出現在內容中,但在關鍵詞定義中將全部爲小寫。

目前我正在使用字符串查找替換組合的案例更改單詞。而且效率很低。

+0

取決於內容的大小以及要匹配的短語的數量和大小。如果你可以給一個代表性的例子,你可能會得到更多的有用(高效等)答案 –

回答

1

如何像

for keyphrase, url in links: 
    content = re.sub('(%s)' % keyphrase, r'<a href="%s">\1</a>' % url, content, flags=re.IGNORECASE) 

因此,例如,在你的榜樣,你可以做

import re 

content = "...And this can be accomplished with the Awesome Method. Blah blah blah...." 
links = [('awesome method', '/path/to/awesome-method')] 

for keyphrase, url in links: 
    content = re.sub('(%s)' % keyphrase, r'<a href="%s">\1</a>' % url, content, flags=re.IGNORECASE) 

# content: 
# '...And this can be accomplished with the <a href="/path/to/awesome-method">Awesome Method</a>. Blah blah blah....' 
+0

謝謝。我一直在使用類似@ michael-laszlo建議的方法。這看起來更乾淨。我只需要調整它以匹配完整的短語,以便它不會替換部分的單詞/短語,比如''blaawesome method''' – anups

1

您可以通過在文本中的位置進行迭代,並建立與基本字符串操作的新文本:

import re 

text = """And this can be accomplished with the Awesome Method. Blah blah blah""" 

keyphrases = [ 
    ('awesome method', 'http://awesome.com/'), 
    ('blah', 'http://blah.com') 
    ] 

new_parts = [] 

pos = 0 
while pos < len(text): 
    replaced = False 
    for phrase, url in keyphrases: 
    substring = text[pos:pos+len(phrase)] 
    if substring.lower() == phrase.lower(): 
     new_parts.append('<a href="%s">%s</a>' % (url, substring)) 
     pos += len(substring) 
     replaced = True 
     break 
    if not replaced: 
    new_parts.append(text[pos]) 
    pos += 1 

new_text = ''.join(new_parts) 
print(new_text) 
0

查看anchorman模塊 - 將您的te xt轉換爲超文本。

import anchorman 

text = "...And this can be accomplished with the Awesome Method. Blah blah blah...." 
links = [{'awesome method': {'value': '/path/to/awesome-method'}}] 
markup_format = { 
    'tag': 'a', 
    'value_key': 'href', 
    'attributes': [ 
     ('class', 'anups') 
    ], 
    'case_sensitive': False 
} 

a = anchorman.add(text, links, markup_format=markup_format) 
print a 
...And this can be accomplished with the <a href="/path/to/awesome-method" 
class="anups">Awesome Method</a>. Blah blah blah....