ex49——创建句子

仍然使用ex46的项目骨架进行测试,NAME文件夹命名为ex49,其中放置需要测试的模块parser.py,也可以使用ex48中的NAME文件,将两次或多次测试一并进行。tests文件夹中放置parser_test.py.
from NAME import module #NAME文件夹名,module模块名

**parse_tests.py**

from nose.tools import *
from ex49 import parse


def test_parse_sentence_normal1():
    # start with subject or object
    word_list = [('noun', 'bear'), ('verb', 'kill'), ('direction', 'east')]
    result = parse.parse_sentence(word_list)
    assert_equal((result.subject, result.verb, result.object), ('bear', 'kill', 'east'))


def test_parse_sentence_normal2():
    # start with verb
    word_list = [('verb', 'kill'), ('direction', 'east')]
    result = parse.parse_sentence(word_list)
    assert_equal((result.subject, result.verb, result.object), ('player', 'kill', 'east'))


def test_raises_type_error():
    """
    If you want to test many assertions about exceptions
    in a single test, you may want to use assert_raises instead
    """
    # middle with stop
    word_list = [('noun', 'bear'), ('stop', 'the'), ('direction', 'east')]
    assert_raises(parse.ParseError, parse.parse_sentence, word_list)


def test_raises_type_error1():
    # start with stop
    word_list = [('stop', 'the'), ('noun', 'bear'), ('direction', 'east')]
    assert_raises(parse.ParseError, parse.parse_sentence, word_list)


def test_raises_type_error2():
    # end with stop
    word_list = [('noun', 'bear'), ('verb', 'kill'), ('stop', 'the')]
    assert_raises(parse.ParseError, parse.parse_sentence, word_list)


 assert_raises = assertRaises(expected_exception, *args, **kwargs) method of nose.tools.trivial.Dummy instance
    Fail unless an exception of class expected_exception is raised
    by the callable when invoked with specified positional and
    keyword arguments. If a different type of exception is
    raised, it will not be caught, and the test case will be
    deemed to have suffered an error, exactly as for an
    unexpected exception.

    If called with the callable and arguments omitted, will return a
    context object used like this::

         with self.assertRaises(SomeException):
             do_something()

    An optional keyword argument 'msg' can be provided when assertRaises
    is used as a context object.

    The context manager keeps a reference to the exception as
    the 'exception' attribute. This allows you to inspect the
    exception after the assertion::

        with self.assertRaises(SomeException) as cm:
            do_something()
        the_exception = cm.exception
        self.assertEqual(the_exception.error_code, 3)
**parse.py**

class ParseError(Exception):
    pass


class Sentence():
    def __init__(self, subject, verb, object):
        # remember we take('noun','princess')tuples and convert them
        self.subject = subject[1]
        self.verb = verb[1]
        self.object = object[1]


def peek(word_list):
    # 若实参有输入,则将列表中第一组元素赋值给word,并返回word元组中第一个元素
    # 若无输入,返回None
    if word_list:
        word = word_list[0]
        return word[0]
    else:
        return None


def match(word_list, expecting):
    # 若实参有输入,则将列表中第一组元素赋值给word,并返回word元组中第一个元素
    # 继续判断,若word第一个元素和期望值相等,返回word,若不相等,返回None
    # 若无输入,返回None
    if word_list:
        word = word_list.pop(0)
        print(word)
        if word[0] == expecting:
            return word
        else:
            return None
    else:
        return None


def skip(word_list, word_type):
    while peek(word_list) == word_type:
        match(word_list, word_type)


def parse_verb(word_list):
    skip(word_list, 'stop')

    if peek(word_list) == 'verb':
        return match(word_list, 'verb')
    else:
        # 当程序出现错误,python会自动引发异常,也可以通过raise显示地引发异常。
        # 一旦执行了raise语句,raise后面的语句将不能执行。
        raise ParseError("Expected a verb next.")


def parse_object(word_list):
    skip(word_list, 'stop')
    next = peek(word_list)

    if next == 'noun':
        return match(word_list, 'noun')
    if next == 'direction':
        return match(word_list, 'direction')
    else:
        raise ParseError("Excepted a noun or direction next.")


def parse_subject(word_list, subj):
    """处理文法部分"""
    # 若当前是verb类型,就满足期望值,pop掉当前,继续后面判断
    verb = parse_verb(word_list)
    # 若当前是noun或direction类型,就满足期望,pop掉当前,继续后面判断
    obj = parse_object(word_list)
    # 返回Sentence类
    return Sentence(subj, verb, obj)


def parse_sentence(word_list):
    # 若(type,word)组第一个组的type是stop,则使用pop将word_list第一个组删除,start赋值为第二个组的type值
    # 若不是,则将第一个组的type赋值给start
    skip(word_list, 'stop')
    start = peek(word_list)
    # 继续判断,若start为'noun',进行match匹配,若匹配成功,将word_list第一个组赋值给subj,并pop删除掉,等待下一次调用判断
    if start == 'noun':
        subj = match(word_list, 'noun')
        # 对当前元组进行文法部分处理
        return parse_subject(word_list, subj)
    elif start == 'verb':
        return parse_subject(word_list, ('noun', 'player'))
    else:
        raise ParseError("Must start with subject, object, or verb not: %s" % start)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值