我正在用 Python、la foobar2000 和 Winamp 编写一个“标题格式”解析器。它基本上是这样工作的:
"%artist% - %title%" -> "The Beatles - Yellow Submarine"
"%title% by $upper(%artist%)" -> "Yellow Submarine by THE BEATLES"
谁能指出我正确的方向?我尝试过 - 但失败了 - 使用正则表达式和 lex/yacc。
EDIT: Along with
%variables%and$functions(), I also have to implement single quotation marks (which surround raw text) and square parentheses (see the references!).
请您参考如下方法:
它必须采用那种确切的格式吗? Python 自己的字符串格式很好:
>>> tags = {'title': 'Yellow Submarine', 'artist': 'The Beatles'}
>>> tags['upperartist'] = tags['artist'].upper()
>>> '{title} by {upperartist}'.format(**tags)
'Yellow Submarine by THE BEATLES'
对于更复杂的事情,我会选择众多 Python templating engines 中的一个。 .模板写起来很有趣——这就是为什么有这么多模板! - 但我敢打赌,其中之一已经可以在您需要时执行。
