创建列表Lexer/Parser



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

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

keyWordList = ['command1', 'command2', 'command3']

以及用户输入字符串:

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

我该如何编写这个函数:

INPUT:
tokenize(userInputList, keyWordList)
OUTPUT:
[['The', 'quick', 'brown'], 'command1', ['fox', 'jumped', 'over'], 'command 2', ['the', 'lazy', 'dog'], 'command3']

我已经写了一个可以识别关键词的标记器,但一直无法找到一种有效的方法来将非关键词组嵌入更深层次的列表中。

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

类似这样的东西:

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

这将返回一个生成器,因此将您的调用封装为一个到list

使用一些正则表达式很容易做到:

>>> reg = r'(.+?)s(%s)(?:s|$)' % '|'.join(keyWordList)
>>> userInput = 'The quick brown command1 fox jumped over command2 the lazy dog command3'
>>> re.findall(reg, userInput)
[('The quick brown', 'command1'), ('fox jumped over', 'command2'), ('the lazy dog', 'command3')]

现在您只需要拆分每个元组的第一个元素。

对于不止一个深度级别,regex可能不是一个好答案。

在这个页面上有一些不错的解析器供您选择:http://wiki.python.org/moin/LanguageParsing

我认为Lepl是个不错的。

试试这个:

keyWordList = ['command1', 'command2', 'command3']
userInput = 'The quick brown command1 fox jumped over command2 the lazy dog command3'
inputList = userInput.split()
def tokenize(userInputList, keyWordList):
    keywords = set(keyWordList)
    tokens, acc = [], []
    for e in userInputList:
        if e in keywords:
            tokens.append(acc)
            tokens.append(e)
            acc = []
        else:
            acc.append(e)
    if acc:
        tokens.append(acc)
    return tokens
tokenize(inputList, keyWordList)
> [['The', 'quick', 'brown'], 'command1', ['fox', 'jumped', 'over'], 'command2', ['the', 'lazy', 'dog'], 'command3']

或者看看PyParsing。一个非常好的小lex解析器组合

最新更新