Learn python the hard way Ex48更复杂的用户输入

经过半天的绸缪,敲击,检错,修正,终于完成了第48小节作者留的作业,虽然代码看起来很糟糕,但是收获不小,我是菜鸟,大神勿喷啊,嘎嘎嘎

#encoding:utf-8
import re


def scan(sentence = None):

    directions = ['north','south','east','west']
    verbs      = ['go','kill','eat']
    stops      = ['the','in','of']
    nouns      = ['bear','princess']
    reward     = []
    global  EN

    if sentence == None:         # 如果是***不传参***,就请求输入
        command = raw_input("Please input your command > ")
        while command == '':    # 如果输入***为空***,就再次请求
            command = raw_input("Please input your command > ")
    else:                       # 如果是***传参***,就用参数作为输入
        command = sentence

    words = command.split()     # 将句子分离为单词序列
    r1 = r"^[0-9]+$"            # 纯数字的正则表达式

    for word in words:
        if re.match(r1,word) != None:# 判断是否能够匹配
            word = int(word)
        if type(word) == str :    # 判断单词是否为***字符串***类型
            for direction in directions:    # 判断单词是否在***方向***列表内
                if direction == word:
                    reward.append(('direction', word))
                    EN = True
                    break
                else:
                    EN = False
            if EN == True:
                continue

            for verb in verbs:              # 判断单词是否在***动词***列表内
                if verb == word:
                    reward.append(('verb', word))
                    EN = True
                    break
                else:
                    EN = False
            if EN == True:
                continue

            for stop in stops:              # 判断单词是否在***顿词***列表内
                if stop == word:
                    reward.append(('stop', word))
                    EN = True
                    break
                else:
                    EN = False
            if EN == True:
                continue

            for noun in nouns:              # 判断单词是否在***名词***列表内
                if noun == word:
                    reward.append(('noun', word))
                    EN = True
                    break
                else:
                    EN = False
            if EN == False:
                reward.append(('error', word))
            
        elif (type(word) == int )or(type(word) == float)\
                or(type(word) == long )or(type(word) == complex):
            reward.append(('number', word))

        else:
            reward.append(('error', word))
            break
    return reward

用nose工具测试结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值