# coding:utf-8
class lexicon(object):
def __init__(self):
# dictionary to find word on
self.directions = ['south', 'north', 'east', 'west']
self.verbs = ['go', 'kill', 'eat']
self.stops = ['the', 'in', 'of']
self.nouns = ['bear', 'princess']
def scan(self, sentence):
result = []
words = sentence.split()
## while(len(words) != 0):
# word = words.pop(0)
for word in words:
## if(self.direction.count(word) == 1):
if word in self.directions:
result.append(('direction', word))
elif word in self.verbs:
result.append(('verb', word))
elif word in self.stops:
result.append(('stop', word))
elif word in self.nouns:
result.append(('noun', word))
else:
try:
word = int(word)
result.append(('number', word))
except ValueError:
result.append(('error', word))
return result
# 测试未实例化 否则会unbound
lexicon = lexicon()
练习48是第一次自己写代码,出现了很多问题。
1.unboud:习题的测试代码没有实例化lexicon,需要在模块中实例化。
2.关于怎么在列表中查找是否存在:
自己写成这样:
if(self.direction.count(word) == 1):后来看到别人的代码:
if word in self.directions:
3.循环的条件:
也是:
while(len(words) != 0): word = words.pop(0)
for word in words:不过学到了不少list的方法。
还有的疑问:
书上是:from ex48 import lexicon
而我:from Game.lexicon import lexicon。 不加'.lexicon'就会importError
查询import的用法,点是子文件夹

本文通过一个简单的Python类实现,介绍了如何创建一个词典匹配类,并详细解释了如何扫描句子以识别方向、动词、停顿词、名词及数字等元素。
9885

被折叠的 条评论
为什么被折叠?



