创建列表Lexer/par

2024-06-23 19:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

以及用户输入字符串:

^{pr2}$

如何编写此函数:

INPUT:

tokenize(userInputList, keyWordList)

OUTPUT:
[['The', 'quick', 'brown'], 'command1', ['fox', 'jumped', 'over'], 'command 2', ['the', 'lazy', 'dog'], 'command3']

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

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


Tags: 数据函数字符串用户parser列表input关键字
3条回答

试试这个:

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']

像这样:

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是个好主意。在

相关问题 更多 >

    热门问题