前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >《Learn python the hard way》Exercise 48: Advanced User Input

《Learn python the hard way》Exercise 48: Advanced User Input

作者头像
s1mba
发布2017-12-28 15:29:34
5920
发布2017-12-28 15:29:34
举报
文章被收录于专栏:开发与安全开发与安全

这几天有点时间,想学点Python基础,今天看到了《learn python the hard way》的 Ex48,这篇文章主要记录一些工具的安装,以及scan 函数的实现。

首先与Ex48相关的章节有前面的Ex46, Ex47,故我们需要先安装一些工具,主要是一些包管理和测试框架的软件:

Install the following Python packages:

  1. pip from http://pypi.python.org/pypi/pip
  2. distribute from http://pypi.python.org/pypi/distribute
  3. nose from http://pypi.python.org/pypi/nose/
  4. virtualenv from http://pypi.python.org/pypi/virtualenv

实际上对于Linux用户来说安装比较简单,首先安装 sudo apt-get install python-pip,接下去的3个都可以使用pip 来安装,即

pip install distribute/nose/virtualenv

模仿Ex46 的描述,新建工程目录为ex48,进而建立以下目录和文件:

setup.py 如下,一些参数可以设置成自己想要的,如NAME 更改为需要测试的模块名:

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

config = {
    'description': 'My Project',
    'author': 'My Name',
    'url': 'URL to get it at.',
    'download_url': 'Where to download it.',
    'author_email': 'My email.',
    'version': '0.1',
    'install_requires': ['nose'],
    'packages': ['NAME'],
    'scripts': [],
    'name': 'projectname'
}

setup(**config)

在ex48 和 tests 目录下各touch新建一个__init__.py 文件。

测试文件 tests/lexicon_tests.py 摘自网站:

from nose.tools import *
from ex48 import lexicon


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

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


def test_stops():
    assert_equal(lexicon.scan("the"), [('stop', 'the')])
    result = lexicon.scan("the in of")
    assert_equal(result, [('stop', 'the'),
                          ('stop', 'in'),
                          ('stop', 'of')])


def test_nouns():
    assert_equal(lexicon.scan("bear"), [('noun', 'bear')])
    result = lexicon.scan("bear princess")
    assert_equal(result, [('noun', 'bear'),
                          ('noun', 'princess')])

def test_numbers():
    assert_equal(lexicon.scan("1234"), [('number', 1234)])
    result = lexicon.scan("3 91234")
    assert_equal(result, [('number', 3),
                          ('number', 91234)])


def test_errors():
    assert_equal(lexicon.scan("ASDFADFASDF"), [('error', 'ASDFADFASDF')])
    result = lexicon.scan("bear IAS princess")
    assert_equal(result, [('noun', 'bear'),
                          ('error', 'IAS'),
                          ('noun', 'princess')])

上面程序中 from ex48 import lexicon 表示从ex48 中 导入lexicon 模块,即现在我们要在ex48 目录下写一个lexicon.py 文件,文件主要是scan 函数的实现,根据网站的提示,自己实现如下:

#!/usr/bin/env python
#coding=utf-8

import re

def convert_number(s):
    try:
        return int(s)
    except ValueError:
        return None


def scan(input_str):

    words = input_str.split(' ')

    pattern = re.compile(r'\d+')

    
    direction_list = ['north', 'south', 'west', 'east', 'down', 'up', 'left', 'right', 'back']
    verb_list = ['go', 'kill', 'stop', 'eat']
    stop_list = ['the', 'in', 'of', 'from', 'at', 'it']
    noun_list = ['door', 'bear', 'princess', 'cabinet']
    sentence_list = []

    for word in words:
        
        bool = pattern.match(word)
        if bool:
            sentence = ('number', convert_number(word))
            sentence_list.append(sentence)
        
        elif word in direction_list:
            sentence = ('direction', word)
            sentence_list.append(sentence)
        
        
        elif word in verb_list:
            sentence = ('verb', word)
            sentence_list.append(sentence)

        elif word in stop_list:
            sentence = ('stop', word)
            sentence_list.append(sentence)

        elif word in noun_list:
            sentence = ('noun', word)
            sentence_list.append(sentence)
        
        else:
            sentence = ('error', word)
            sentence_list.append(sentence)
    
    return sentence_list

程序中使用正则表达式来匹配数字字符串,请google re 模块之。

执行测试命令,即使用lexicon_tests.py 去测试lexicon.py 里面的函数,输出如下:

simba@ubuntu:~/Documents/code/python/projects/ex48$ nosetests ......... Ran 6 tests in 0.007s OK

参考 :http://learnpythonthehardway.org/book/ex48.html

后记:

如果在使用pip or easy_install 时提示url不正确,可以临时修改或者修改配置文件中的index-url为国内镜像点。

下载完成,编译安装过程中如果提示不存在python.h,可以 sudo apt-get install python-dev     or  yum install python-devel

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2013-09-27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档