【问题标题】:most efficient way to parse this scripting language解析这种脚本语言的最有效方法
【发布时间】:2012-07-18 22:04:20
【问题描述】:

我正在为早已过时的文本编辑器的脚本语言实现解释器,但在让词法分析器正常工作时遇到了一些麻烦。

以下是该语言有问题的部分的示例:

T
L /LOCATE ME/
C /LOCATE ME/CHANGED ME/ * *
C ;CHANGED ME;CHANGED ME AGAIN; 1 *

/ 字符似乎引用字符串,并且还充当sed 类型语法中C (CHANGE) 命令的分隔符,尽管它允许任何字符作为分隔符。

到目前为止,我可能已经实现了大约一半的最常用命令,仅使用 parse_tokens(line.split())。这又快又脏,但效果却出奇的好。

为避免编写自己的词法分析器,我尝试了shlex。

它工作得很好,除了CHANGE 情况:

import shlex

def shlex_test(cmd_str):
    lex = shlex.shlex(cmd_str)
    lex.quotes = '/'
    return list(lex)

print(shlex_test('L /spaced string/'))
# OK! gives: ['L', '/spaced string/']

print(shlex_test('C /spaced string/another string/ * *'))
# gives   : ['C', '/spaced string/', 'another', 'string/', '*', '*']
# desired : any format that doesn't split on a space between /'s

print(shlex_test('C ;a b;b a;'))
# gives   : ['C', ';', 'b', 'a', ';', 'a', 'b', ';']
# desired : same format as CHANGE command above

任何人都知道实现此目的的简单方法(使用shlex 或其他方式)?

编辑:

如果有帮助,这里是帮助文件中给出的CHANGE 命令语法:

'''
C [/stg1/stg2/ [n|n m]]

    The CHANGE command replaces the m-th occurrence of "stg1" with "stg2"
for the next n lines.  The default value for m and n is 1.'''

同样难以标记 X 和 Y 命令:

'''
X [/command/[command/[...]]n]
Y [/command/[command/[...]]n]

    The X and Y commands allow the execution of several commands contained
in one command.  To define an X or Y "command string", enter X (or Y)
followed by a space, then individual commands, each separated by a
delimiter (e.g. a period ".").  An unlimited number of commands may be
placed in the X or Y command string.  Once the command string has been
defined, entering X (or Y) followed optionally by a count n will execute
the defined command string n times.  If n is not specified, it will
default to 1.'''

【问题讨论】:

  • 您可以访问语言定义吗?如果是这样,相关部分的引用可能对我们所有人都有用。
  • @Marcin 我从帮助文件中添加了一些相关信息,这是我拥有的所有文档。
  • 我不知道shlex,但我认为regex (re) 也很有用。
  • 现在你有两个以上的问题。
  • 我认为 pyparsing 可能是更好的选择。

标签: python lexer shlex


【解决方案1】:

问题可能是/ 不代表引号,而仅代表分隔符。我猜第三个字符总是用来定义分隔符。此外,您不需要输出中的/ 或;,对吗?

我刚刚对 L 和 C 命令案例进行了拆分:

>>> def parse(cmd):
...     delim = cmd[2]
...     return cmd.split(delim)
...
>>> c_cmd = "C /LOCATE ME/CHANGED ME/ * *"
>>> parse(c_cmd)
['C ', 'LOCATE ME', 'CHANGED ME', ' * *']

>>> c_cmd2 = "C ;a b;b a;"
>>> parse(c_cmd2)
['C ', 'a b', 'b a', '']

>>> l_cmd = "L /spaced string/"
>>> parse(l_cmd)
['L ', 'spaced string', '']

对于可选的" * *" 部分,您可以在最后一个列表元素上使用split(" ")。

>>> parse(c_cmd)[-1].split(" ")
['', '*', '*']

【讨论】:

  • 不幸的是,它不是总是第三个字符,但我会尝试这种方法并回帖,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-09
  • 2010-10-11
  • 2011-02-14
  • 1970-01-01
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多