2011-10-20 29 views
2

我正在開發一個django項目,並且有一個模型,其中包含一個列表things。在整個網站中,我可能會在其他模型中輸入非結構化文本。在顯示一個頁面時,我想分析非結構化文本,對thing.slug的任何參考,幷包括到thing.get_absolute_url的鏈接。解析字典術語的非結構化文本以包含術語鏈接

我會假設一個應用程序需要由一個自定義templatetag,即解析object.text,它採用類似正則表達式解析器從所有things的字典匹配任何thing.slug條款。

舉個例子:

我有thingA和thingB,但想thingC。

將被修改爲:

I have <a href="/things/a">thingA</a> and <a href="/things/b">thingB</a>, but would like <a href="/things/c">thingC</a>. 

如果有已經這樣做了一個Django應用程序,太棒了!否則,有關如何最好地實現這一點的任何建議,我們感激。我也喜歡jquery等其他建議,儘管我不太熟悉它。

+1

匹配是怎麼回事?你說'thingA'應該轉換成'/ things/a',但是應該把'thingamajiggy'轉換成'thing/amajiggy'?它是駝峯,所以'thingThatIWant'變成了'/ things/that/i/want'? – jro

+0

如果你對django很熟悉,我的模型有'title'和'slug'的字段,所以slug就是urlpattern匹配的內容。 – erikankrom

+0

@erikankrom:這將有助於更新您的問題,準確顯示'thingamajiggy'和'thingThatIWant'應該如何處理。它也有助於在問題中包含模型的相關部分。 –

回答

1
urls = dict((thing.slug, thing.get_absolute_url) for thing in things) 
for word in object.text.split(): 
    if word in urls: 
    result.append('<a href="'+urls[words]+'">'+word+'</a> ') 
    else 
    result.append(word+' ') 
+0

我喜歡這種方法。在模型post_save中,我可以通過芹菜將object.text解析爲object.html。 – erikankrom

1

重新模塊具有子()功能是專爲這種搜索和替換的。

搜索從非結構化文本的其餘部分區分「事」,構建適當的替換字符串的模式:

>>> import re 
>>> s = 'I have thing.slug and thing.foo, but would like thing.foo' 
>>> re.sub(r'(\w+)\.(\w+)', r'<a href="/\1/\2">\1.\2</a>', s) 
'I have <a href="/thing/slug">thing.slug</a> and <a href="/thing/foo">thing.foo</a>, but would like <a href="/thing/foo">thing.foo</a>' 

這是更可靠(更不容易出錯)是您爲模式「事物」更有特色:

>>> s = 'I have {thing.slug} and {thing.foo}, but would like {thing.foo}' 
>>> re.sub(r'{(\w+)\.(\w+)}', r'<a href="/\1/\2">\1.\2</a>', s) 
'I have <a href="/thing/slug">thing.slug</a> and <a href="/thing/foo">thing.foo</a>, but would like <a href="/thing/foo">thing.foo</a>'