python - 创建列表词法分析器/解析器

标签 python algorithm parsing lexer tokenize

我需要创建一个词法分析器/解析器来处理可变长度和结构的输入数据。

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

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 中。

关于python - 创建列表词法分析器/解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8866485/

相关文章:

algorithm - 给定一个整数数组和一个数字 n,计算使用整数求和到 n 的方法数

parsing - 使用 Go 解析 Go 时间戳

python - 正则表达式 : may or may not contain a string

python - Matplotlib python show() 立即返回

php - 如何从嵌套对象构建嵌套数组?

algorithm - 取最高项的算法的时间复杂度

parsing - 从 dhcp 输出作为单行输出

python - 如何将 YAML 文件解析/读取到 Python 对象中?

python - 在空数据帧上调用 parse_date

python - 使用 Python Mechanize 触发 onclick 按钮