learn python the hard way 的ex48

在学习 用learn python the hard way的ex48   他只给了一个测试文件,而源文件要求你自己写,你时常会出现这个错误。

unboundlocalerror:local variable ‘xxx’  reference before assignment

我也是初学者,一下只是我的个人见解。

这是因为  他的测试文件中 没有给你的类实例化,assert_equal(lexicon.scan("the"),[('stop','the')])  在这里你需要实例化你的类,他给的代码需要你来添加实例化的部分。


下面是我做的测试部分


from nose.tools import *
from ex48 import lexicon


def test_directions():
	lexicon1=lexicon('1')
	assert_equal(lexicon1.scan("north"),[('direction','north')])
	lexicon1=lexicon('1')
	result = lexicon1.scan("north south east")
	assert_equal(result,[('direction','north'),
						('direction','south'),
						('direction','east')])
def test_verbs():
	lexicon1=lexicon('2')
	assert_equal(lexicon1.scan("go"),[('verb','go')])
	lexicon1=lexicon('2')
	result = lexicon1.scan("go kill eat")
	assert_equal(result,[('verb','go'),
						('verb','kill'),
						('verb','eat')])

def test_stops():
	lexicon1=lexicon('3')
	assert_equal(lexicon1.scan("the"),[('stop','the')])
	lexicon1=lexicon('3')
	result = lexicon1.scan("the in of")
	assert_equal(result,[('stop','the'),
						('stop','in'),
						('stop','of')])
						
def test_nouns():
	lexicon1=lexicon('4')
	assert_equal(lexicon1.scan("bear"),[('noun','bear')])
	lexicon1=lexicon('4')
	result = lexicon1.scan("bear princess")
	assert_equal(result,[('noun','bear'),
						('noun','princess')])
						
def test_numbers():
	lexicon1=lexicon('5')
	assert_equal(lexicon1.scan("1234"),[('number',1234)])
	lexicon1=lexicon('5')
	result = lexicon1.scan("bear IAS princess")
	assert_equal(result,[('noun','bear'),
						('error','IAS'),
						('noun','princess')])


下面是我写的类:

class lexicon(object):
	def __init__(self,name):
		self.direction=('north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back')
		self.verb=('go','stop','kill','eat')
		self.stop=('the','in','of','from','at','it')
		self.noun=('door','bear','princess','cabinet')
		self.result=[]
	def comvert_number(self,s):
		try:
			return int(s)
		except:
			return None
	def scan(self,input):
		words=input.split(' ')
		for word in words:
			if word in self.direction:
				self.result.append(('direction',word))
			elif word in self.verb:
				self.result.append(('verb',word))
			elif word in self.stop:
				self.result.append(('stop',word))
			elif word in self.noun:
				self.result.append(('noun',word))
			elif (self.comvert_number(word)!=None): 
				self.result.append(('number',self.comvert_number(word)))
			else:
				self.result.append(('error',word))
		return self.result



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值