这是照着书自己的创意
第一版
#coding=utf-8
lexicon={
'north':'direction',
'south':'direction',
'east':'direction',
'1':'number',
'3':'number',}
def scan(sentence):
words=sentence.split()
result=[]
for word in words:
number ="1"
number1="3"
if number ==word or number1==word :
pair=(lexicon[word],eval(word))
result.append(pair)#添加
print result
else:
pair =(lexicon[word],word)
result.append(pair)#添加
print result
return result
scan('north south east 1 3')
这是在网上大神给的方案
lexicon = {
'north': ('direction', 'north'),
'south': ('direction', 'south'),
'east': ('direction', 'east'),
'west': ('direction', 'west'),
'go': ('verb', 'go'),
'kill': ('verb', 'kill'),
'eat': ('verb', 'eat'),
'the': ('stop', 'the'),
'in': ('stop', 'in'),
'of': ('stop', 'of'),
'bear': ('noun', 'bear'),
'princess': ('noun', 'princess'),
}
def isnum(Num):
try:
return int(Num)
except:
return None
def scan(sentence):
words = sentence.split()
result = []
for word in words:
if isnum(word):
result.append(('number', int(word)))
elif word in lexicon.keys():
result.append(lexicon[word])
else:
result.append(('error', word))
return result
大神方法转载https://blog.csdn.net/riario/article/details/52985360
但是他的方法没办法达到 Zed的想法
于是更改如下
#-*-coding=utf-8-*-
lexicon={
'north':'direction',
'south':'direction',
'east':'direction',
'go':'verb',
'kill':'verb',
'eat':'verb',
'the':'stop',
'in':'stop',
'of':'stop',
'bear':'noun',
'princess':'noun',
'1234':'number',
'3':'number',
'91234':'number',
'ASDFADFASDF':'error',
'bear':'noun',
'IAS':'error',
'open':'error'}
def isnum(Num):
try:
return int(Num)
except:
return None
def scan(sentence):
words = sentence.split()
result = []
for word in words:
if isnum(word):
pair=('number',int(word))
result.append(pair)
elif word in lexicon.keys():
ww=lexicon[word]
pair=(ww,word)
result.append(pair)#添加
else:
result.append((word, 'error'))
return result
#else:
# convert_number())
#return result
感觉全网只有我写出来的即时感,啪啪啪啪打脸 哈哈哈,这是达到的效果 明天继续研究。。。。在上班时间学python爽啊!!!