NoneType错误,使用来自ply的lex.lex

时间:2013-01-25 01:31:50

标签: python python-2.7 ply

我正在尝试使用ply解析一个单词/短语列表并使用该库中的lex.lex。

我之前在单词列表中使用了lex.lex,它运行正常,只需使用for循环输入词法分析器。

但我不断收到以下错误

Traceback (most recent call last):
File "<pyshell#56>", line 2, in <module>
mylexer.input(a)
File "ply\lex.py", line 253, in input
c = s[:1]
TypeError: 'NoneType' object has no attribute '__getitem__'

我想在这个场合试图lex的列表是解析json,据我所知是唯一的区别,从之前的lexing实际上有效吗?

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

ply.lex 的相关代码是:

def input(self,s):
    # Pull off the first character to see if s looks like a string
    c = s[:1]
    if not isinstance(c,StringTypes):
        raise ValueError("Expected a string")
    self.lexdata = s
    self.lexpos = 0
    self.lexlen = len(s)

看起来您的问题出在您的电话mylexer.input(a)中。 a 变量是而不是单词列表。

有时这是由您生成单词列表的方式引起的。例如,这会导致您看到的相同错误:

words = 'the quick brown fox'.split()
a = words.sort()                   # Note, this returns None
mylexer.input(a)                   # The lexer won't be happy with None

答案 1 :(得分:0)

好的

谢谢,手工阅读完列表后,似乎其中一个json键没有值,后者变为None。