我需要创建一个词法分析器/解析器来处理可变长度和结构的输入数据。
假设我有一个保留关键字列表:
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/