问题原有网页:http://learnpythonthehardway.org/book/ex48.html
代码可以这样写:
#class lexicon(object):
# def __init__(self):
# self.result=[]
def scan(sentence):
result = []
words=sentence.split()
length = len(words);
while words:
if words[0] in ['east','west','north','south']:
result.append(('direction',words[0]))
elif words[0] in ['go', 'kill', 'stop','eat']:
result.append(('verb',words[0]))
elif words[0] in ['door','bear','princess','cabinet']:
result.append(('noun',words[0]))
elif words[0] in['the','in','of','from','at','it']:
result.append(('stop',words[0]))
elif convert_number(words[0]):
num = int(words[0])
result.append(('number',num))
else:
result.append(('error',words[0]))
words = words[1:]
return result
def convert_number(s):
try:
return int(s)
except ValueError:
return None
本文详细解析了一个Python代码实现的词汇类别扫描器,该扫描器用于解析输入句子并将其分解为不同的词汇类别,如方向、动词、名词等。通过代码实例展示了如何根据词汇的不同类型进行分类,并提供了相应的函数实现。
337

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



