创建列表Lexer/Parser

Joe*_*ett 2 python algorithm parsing tokenize lexer

我需要创建一个lexer/parser来处理可变长度和结构的输入数据.

假设我有一个保留关键字列表:

keyWordList = ['command1', 'command2', 'command3']
Run Code Online (Sandbox Code Playgroud)

和用户输入字符串:

userInput = 'The quick brown command1 fox jumped over command2 the lazy dog command 3'
userInputList = userInput.split()
Run Code Online (Sandbox Code Playgroud)

我将如何编写此函数:

INPUT:

tokenize(userInputList, keyWordList)

OUTPUT:
[['The', 'quick', 'brown'], 'command1', ['fox', 'jumped', 'over'], 'command 2', ['the', 'lazy', 'dog'], 'command3']
Run Code Online (Sandbox Code Playgroud)

我编写了一个可以识别关键字的标记化程序,但是无法找到一种将非关键字组嵌入到更深层次的列表中的有效方法.

RE解决方案是受欢迎的,但我真的希望看到底层算法,因为我可能会将应用程序扩展到其他对象的列表而不仅仅是字符串.

Fre*_*Foo 5

像这样的东西:

def tokenize(lst, keywords):
    cur = []
    for x in lst:
        if x in keywords:
            yield cur
            yield x
            cur = []
        else:
            cur.append(x)
Run Code Online (Sandbox Code Playgroud)

这将返回一个生成器,因此将您的调用包装在一个中list.