# -*- coding:utf-8 -*-
def scan(sentence):
# 将已知的词汇放入列表中存储
directions = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
verbs = ['go', 'stop', 'kill', 'eat']
stops = ['the', 'in', 'of', 'from', 'at', 'it']
nouns = ['door', 'bear', 'princess', 'cabinet']
tup = []
# 将句子中的单词已空格分开并存在列表中
words = sentence.split()
# 遍历words中元素,以元组的形式给单词分类
for word in words:
# word = word.lower() # 全部转成小写
if word in directions:
sen = ('direction', word)
elif word in verbs:
sen = ('verb', word)
elif word in stops:
sen = ('stop', word)
elif word in nouns:
sen = ('noun', word)
else: # 测试是否是数字
try:
word = int(word)
sen = ('number', word)
except ValueError:
sen = ('error', word)
tup.append(sen)
return tup
小结: 第一次接触到元组,元组其实就是一个不能修改的列表。使用测试用例也不是想象中那么省事呀(- _-!)。
更复杂的用户输入之scan函数ex48(lexicon.py)
最新推荐文章于 2023-09-28 17:13:15 发布