《笨办法学python3》习题48代码

在《笨办法学python3》习题48遇到了一点问题,以此记录一下

编写扫描器
因为 lexicon_tests.py文件调用时用的是from ex48 import lexicon而不是 from ex48.lexicon import lexicon所以不用类来写这个文件,不然会出现module 'ex48.lexicon' has no attribute 'scan'的情况

用类写请将lexicon_tests.py文件中from ex48 import lexicon改为 from ex48.lexicon import Lexicon
Lexicon为类名

以下为:lexicon.py

# _*_ coding:utf-8 _*_
# 因为 lexicon_tests.py 文件调用时用的是from ex48 import lexicon 而不是 from ex48.lexicon import lexicon
# 所以不用类来写这个文件,不然会出现找不到scan函数的情况
# 用类写请将lexicon_tests.py 文件中from ex48 import lexicon 改为 from ex48.lexicon import Lexicon // Lexicon为类名

directions = ('south','north','west','east','center')
verbs = ('go','kill','eat','run','tell','shoot','sing','love')
stops = ('the','in','of','to','via')
nouns = ('bear','princess','MissHei','tiger','dragon')

def scan(stuff):
    words = stuff.split() #默认空格和其他符号 
    sentence = []

    for word in words:
        try:
            if word in directions:
                sentence.append(('direction',word))
            elif word in verbs:
                sentence.append(('verb',word))
            elif word in stops:
                sentence.append(('stop',word))
            elif word in nouns:
                sentence.append(('noun',word))
            else: 
                word = int(word)
                sentence.append(('number',word))
        except ValueError:
            sentence.append(('error',word))
    return sentence

# 手动测试函数
def test():  
    print(scan("Let's go go go "))

if __name__ == "__main__": # 直接运行此文件时运行,调用此文件时不运行
    test()

手动测试可进入ex48文件夹后,运行python lexicon.py
运行结果:

PS C:\pycharmtest\projects\ex48> python .\lexicon.py
[('error', "Let's"), ('verb', 'go'), ('verb', 'go'), ('verb', 'go')]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值