笨办法学python笔记(48)更复杂的用户输入,答案

这是照着书自己的创意
第一版

#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爽啊!!!在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值