我写了一个自定义的语言Python的解析器和现在我有这样的事情:如何改进我的解析技巧?
re1 = re.compile(r"...")
re2 = re.compile(r"...")
re3 = re.compile(r"...")
re4 = re.compile(r"...")
...
...
现在我正在读输入文件和每行,如果我找到一个特定的关键字,然后我使用特定的正则表达式。显然,这是使我的生活变成地狱,因为我在做这样的事情:
if line.find("keyword1") >= 0
# Uses re1 to match the string
invoke_handler1()
elif line.find('keyword2") >= 0
# Uses re2 to match the string
invoke_handler2()
...
与此同时,我不想给定线路与所有可能的正则表达式匹配,因为那将是一种浪费。在不丢弃我写下来的所有内容之前,是否有一种解决这个问题的优雅方法,并使其更加高效和易读?
你有没有考虑过使用真正的[parser](http://wiki.python.org/moin/LanguageParsing)? – nmichaels 2011-03-07 20:52:52
这是什么解析器?你能详细说明你正在解析的文本/代码的复杂性吗? – 2011-03-07 20:54:10
@nmichaels:我想我需要更多地了解这一点。谢谢! @Nicolas Buduroi:我正在解析一个字节码反汇编。 – Legend 2011-03-07 20:55:44