2011-08-22 32 views
4

我試圖來標記在Python以下輸入:符號化複雜的輸入

text = 'This @[email protected] is "neither":/defn/neither complete[1] *nor* trite, *though _simple_*.' 

我想產生類似下面的同時避免使用正則表達式:

tokens = [ 
     ('text', 'This '), 
     ('enter', 'code'), 
      ('text', "example") 
     ('exit', None), 
     ('text', ' is '), 
     ('enter', 'a'), 
      ('text', "neither"), 
      ('href', "/defn/neither"), 
     ('exit', None), 
     ('text', ' complete'), 
     ('enter', 'footnote'), 
      ('id', 1), 
     ('exit', None), 
     ('text', ' '), 
     ('enter', 'strong'), 
      ('text', 'nor'), 
     ('exit', None), 
     ('text', ' trite, '), 
     ('enter', 'strong'), 
       ('text', 'though '), 
       ('enter', 'em'), 
        ('text', 'simple'), 
       ('exit', None), 
     ('exit', None), 
     ('text', '.') 
    ] 

假裝以上是由發電機產生的。我的current implementation的作品,雖然代碼有點可怕,不容易擴展到支持鏈接。

任何援助將不勝感激。

已更新,將所需的語法從複雜的嵌套列表結構更改爲簡單的元組流。對我們人類的縮進。在鏈接文本中格式化是可以的。這裏是a simple parser,它生成我正在尋找的lexing結果,但仍然不處理鏈接或腳註。

+1

有趣。爲什麼你想避免使用正則表達式的任何特定原因? – NullUserException

+0

['shlex'](http://docs.python.org/library/shlex.html)可以爲您提供幫助並且開箱即用 – JBernardo

+0

@NullUserException正則表達式比當前解決方案慢幾個數量級,並且變得複雜當你開始處理嵌套規則集時。 – amcgregor

回答

1

那麼,here's a more complete parser具有足夠的可擴展性來做我將來可能需要的任何東西。它只花了三個小時。這不是非常快,但通常我寫的解析器類的輸出總是被高速緩存。即使使用這個標記器和解析器,我的完整引擎仍然會以默認python-textile渲染器的75%的SLoC時鐘速度運行,同時保持稍微更快的速度。沒有正則表達式。

腳註解析仍然存在,但與鏈接解析相比,這是微不足道的。輸出(截至本貼子)爲:

tokens = [ 
    ('text', 'This '), 
    ('enter', 'code'), 
     ('text', 'example'), 
    ('exit', None), 
    ('text', ' is '), 
    ('enter', 'a'), 
     ('text', 'neither'), 
     ('attr', ('href', '/defn/neither')), 
    ('exit', None), 
    ('text', ' complete[1] '), 
    ('enter', 'strong'), 
     ('text', 'nor'), 
    ('exit', None), 
    ('text', ' trite, '), 
    ('enter', 'strong'), 
     ('text', 'though '), 
     ('enter', 'em'), 
      ('text', 'simple'), 
     ('exit', None), 
    ('exit', None), 
    ('text', '.') 
] 
+0

作爲關於速度差異的簡要說明:解析器的當前狀態在13.4毫秒內分析項目README(https://github.com/marrow/marrow.texting/blob/develop/README.textile)與紡織品在同一文檔上需要249毫秒,生成幾乎相同的HTML標記。哎喲! – amcgregor