【发布时间】:2016-04-02 14:44:38
【问题描述】:
我正在使用 Python 来实现一个 Earley Parser,它的上下文无关规则定义如下:
class Rule:
def __init__(self,string,i,j,dot):
self.i = 0
self.j = 0
self.dot = 0
string = string.split('->')
self.lhs = string[0].strip()
self.rhs1 = string[1].strip()
self.rhs = []
self.rhs1 = self.rhs1.split(' ')
for word in self.rhs1:
if word.strip()!= '':
self.rhs.append(word)
def __eq__(self, other):
if self.i == other.i:
if self.j == other.j:
if self.dot == other.dot:
if self.lhs == other.lhs:
if self.rhs == other.rhs:
return True
return False
为了检查图表数组中是否存在 Rule 类的对象,我使用了以下方法:
def enqueue(self, entry, state):
if state in self.chart[entry]:
return None
else:
self.chart[entry].append(state)
chart 是一个数组,应该包含Rule 类的对象列表:
def __init__(self, words):
self.chart = [[] for i in range(len(words))]
我进一步检查chart[entry]中的规则是否存在如下(如果不存在,则简单地追加):
def enqueue(self, entry, state):
if state in self.chart[entry]:
return None
else:
self.chart[entry].append(state)
但是这给了我一个错误
TypeError: 'in <string>' requires string as left operand, not classobj
为了避免这种情况,我什至在类本身中声明了一个__eq__ 函数,但它似乎不起作用。任何人都可以帮助我吗?
【问题讨论】:
-
您是否 100% 确定
self.chart[entry]是一个列表?从错误消息来看,self.chart[entry]似乎是一个字符串。如果您在enqueue的开头执行print type(self.chart[entry]),会出现什么情况? -
将
class rule:更改为class Rule(object): -
@All,编辑了上面的代码。
-
@Kevin 它说类型