direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
verbs = ['go', 'stop', 'kill', 'eat']
stop = ['the', 'in', 'of', 'from', 'at', 'it']
nouns = ['door', 'bear', 'princess', 'cabinet']
numbers = [i for i in range(10)]
class lexicon(object):
def scan(self, sentence):
self.sentence = sentence
self.words = sentence.split()
for word in self.words:
if word is direction:
word = ('direction','%s' % word)
return word
Run Code Online (Sandbox Code Playgroud)
http://learnpythonthehardway.org/book/ex48.html是我正在研究的,我不知道为什么我的程序没有通过测试.当我运行nosetests时,我得到了这个错误.
ERROR: tests.ex48_tests.test_directions
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/tplaw/Public/projects/installs/venv/lib/python2.7/site-packages/nose/case.py", line 197, in runTest …Run Code Online (Sandbox Code Playgroud) direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
class Lexicon(object):
def scan(self, sentence):
self.sentence = sentence
self.words = self.sentence.split()
self.term = []
for word in self.words:
if word in direction:
part = ('direction','%s' % word)
self.term.append(word)
return self.term
lexicon = Lexicon()
Run Code Online (Sandbox Code Playgroud)
当我进入时,lexicon.scan('north south east')我期待着回归给我[('direction','north'),('direction','south'),('direction','east')].相反,我得到了['north'].这是我希望程序整体上做的事情.
这是一个更大的计划的一部分.这是我想要做的.
这是我正在尝试的:
def scan(self, sentence):
self.term = []
for word in sentence.split():
if word in direction:
self.term.append(('direction', word))
elif word in verbs:
self.term.append(('verb', word))
elif word in stop:
self.term.append(('stop', word))
elif word in nouns:
self.term.append(('noun', word))
elif type(int(word)) == 'int':
self.term.append(('number', int(word)))
else:
self.term.append(('error', word))
return self.term
print lexicon.scan('12 1234')
Run Code Online (Sandbox Code Playgroud)
这是一个类中的方法,print语句在外面.我关心和遇到麻烦的部分是这样的:
elif type(int(word)) == int:
self.term.append(('number', int(word)))
Run Code Online (Sandbox Code Playgroud)
它适用于任何自然数[1,无穷大]
编辑:当我尝试扫描时遇到问题('ASDFASDFASDF')