解析此脚本语言的最有效方法

Rob*_*ati 7 python lexer shlex

我正在为一个长期过时的文本编辑器的脚本语言实现一个解释器,而我在让词法分析器正常工作方面遇到了一些麻烦.

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

T
L /LOCATE ME/
C /LOCATE ME/CHANGED ME/ * *
C ;CHANGED ME;CHANGED ME AGAIN; 1 *
Run Code Online (Sandbox Code Playgroud)

/人物似乎引用字符串,也充当分隔符C(CHANGE在)命令sed型语法,但它允许任何字符作为分隔符.

我可能实现了大约一半最常见的命令,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
Run Code Online (Sandbox Code Playgroud)

任何人都知道一个简单的方法来完成这个(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.'''
Run Code Online (Sandbox Code Playgroud)

同样难以标记化XY命令:

'''
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.'''
Run Code Online (Sandbox Code Playgroud)

sev*_*rce 0

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

我刚刚仅针对 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', '']
Run Code Online (Sandbox Code Playgroud)

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

>>> parse(c_cmd)[-1].split(" ")
['', '*', '*']
Run Code Online (Sandbox Code Playgroud)