笨办法学python3 练习48

笨办法学python3 练习48


direction = ['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
verb = ['go', 'stop', 'kill', 'eat']
stop = ['the', 'in', 'of', 'from', 'at', 'it', 'to']
noun = ['door', 'bear', 'princess', 'cabinet']

def scan(stuff):
    words = stuff.split()    # 通过指定分隔符对字符串进行切片,切片后为list
    sentence = []
    for word in words:
        print('words======',words)
        try:
            if word in direction:
                sentence.append(('direction',word))   #append  函数本身需要一个括号,值转换换要一个括号
            elif word in verb:
                sentence.append(('verb',word))
            elif word in stop:
                sentence.append(('stop',word))
            elif word in noun:
                sentence.append(('noun',word))
            else:
                word = int(word)
                sentence.append(('number',word))
        except ValueError:
            sentence.append(('error',word))
    return sentence
from nose.tools import *
from Lexicon import *

def test_directions():
    assert_equal(scan('north'),[('direction','north')])
    result = scan('north south east')
    assert_equal(result,[('direction','north'),
                         ('direction','south'),
                         ('direction','east')])

def test_verbs():
    assert_equal(scan('go'),[('verb','go')])
    result = scan('go kill eat')
    assert_equal(result,[('verb','go'),
                         ('verb','kill'),
                         ('verb','eat')])

def test_stop():
    assert_equal(scan('the'),[('stop','the')])
    result = scan('the in of')
    assert_equal(result,[('stop','the'),
                         ('stop','in'),
                         ('stop','of')])
def test_nouns():
    assert_equal(scan('bear'),[('noun','bear')])
    result = scan('bear princess')
    assert_equal(result,[('noun','bear'),
                  ('noun','princess')])
def test_numbers():
    assert_equal(scan('1234'),[('number',1234)])
    result = scan('3 91234')
    assert_equal(result,[('number',3),
                          ('number',91234)])

def test_errors():
    assert_equal(scan('ASDFADFASDF'),[('error', 'ASDFADFASDF')])
    result = scan('bear IAS princess')
    print('1',result)
    assert_equal(result,[('noun', 'bear'),
                         ('error', 'IAS'),
                         ('noun','princess')])


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值