这几天有点时间,想学点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 的描述,新建工程目录为ex47,进而建立以下目录和文件:

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

 Python Code 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

 
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)

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

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

 Python Code 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

 
from nose.tools 
import *


from ex47 
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', 
)])

    result = lexicon.scan(
"3 91234")

    assert_equal(result, [(
'number', 
),

                          (
'number', 
)])

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 ex47 import lexicon 表示从ex47 中 导入lexicon 模块,即现在我们要在ex47 目录下写一个lexicon.py 文件,文件主要是scan 函数的实现,根据网站的提示,自己实现如下:

 Python Code 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

 
#!/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/ex47$ nosetests
.........
----------------------------------------------------------------------
Ran 9 tests in 0.081s

OK

为什么是9个tests 呢,上面只有6个,实际上我在ex47 下还有个game.py,而针对这个模块的测试文件game_tests.py也存在tests 目录下,且里面有3个test, 故这个项目总的测试个数是9个,需要针对一个模块写一个测试文件。

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

《Learn python the hard way》Exercise 48: Advanced User Input的更多相关文章

  1. 《用Python做HTTP接口测试》学习感悟

    机缘巧合之下,报名参加了阿奎老师发布在"好班长"的课程<用Python做HTTP接口测试>,报名费:15rmb,不到一杯咖啡钱,目前为止的状态:坚定不移的跟下去,自学+ ...

  2. 推荐《用Python进行自然语言处理》中文翻译-NLTK配套书

    NLTK配套书<用Python进行自然语言处理>(Natural Language Processing with Python)已经出版好几年了,但是国内一直没有翻译的中文版,虽然读英文 ...

  3. 《Python3网络爬虫开发实战》PDF+源代码+《精通Python爬虫框架Scrapy》中英文PDF源代码

    下载:https://pan.baidu.com/s/1oejHek3Vmu0ZYvp4w9ZLsw <Python 3网络爬虫开发实战>中文PDF+源代码 下载:https://pan. ...

  4. 《精通Python爬虫框架Scrapy》学习资料

    <精通Python爬虫框架Scrapy>学习资料 百度网盘:https://pan.baidu.com/s/1ACOYulLLpp9J7Q7src2rVA

  5. 《基于Python的GMSSL实现》课程设计个人报告

    <基于Python的GMSSL实现>课程设计个人报告 一.基本信息 姓名:刘津甫 学号:20165234 题目:GMSSL基于python的实现 指导老师:娄嘉鹏 完成时间:2019年5月 ...

  6. (附音视频、PPT地址)《打开Python这扇窗》分享总结

    0.导读 2016年最新开发语言排行榜中,Python已经跃居第三,仅次于C.JAVA.掌握Python已经成为时下运维圈的共识,更让人期待的是,本次公开课分享的嘉宾自身就长期专注Python.Doc ...

  7. 笔记之《用python写网络爬虫》

    1 .3 背景调研 robots. txt Robots协议(也称为爬虫协议.机器人协议等)的全称是"网络爬虫排除标准"(Robots Exclusion Protocol),网站 ...

  8. 《用Python玩转数据》项目—线性回归分析入门之波士顿房价预测(二)

    接上一部分,此篇将用tensorflow建立神经网络,对波士顿房价数据进行简单建模预测. 二.使用tensorflow拟合boston房价datasets 1.数据处理依然利用sklearn来分训练集 ...

  9. 《用Python做HTTP接口测试》练习资料共享

    原作者代码在https://github.com/akuing/python-http-interface-test

随机推荐

  1. (ubuntu)在andorid andk工程中使用ccache加速编译速度

    环境 系统:Linux luogw-pc 3.5.0-36-generic #57~precise1-Ubuntu SMP Thu Jun 20 18:21:09 UTC 2013 x86_64 x8 ...

  2. android源代码百度网盘分享

    转载请标明出处:  http://blog.csdn.net/yujun411522/article/details/46334123 本文出自:[yujun411522的博客] 近期在使用Ubunt ...

  3. 金典 SQL笔记(4)

    由于在本地笔记上写的.CSDN markdown编辑器仅仅支持.md格式导入, 图片没办法直接导进去.写的多了懒的一张一张图片切图上传; 直接整个文章切成图片上传上去了. watermark/2/te ...

  4. 数据持久化之CoreData

    再次回归博客园, 已经实属不易了, 面临这近期忙忙碌碌的项目开发, 虽然并不是完全的没有闲暇时间, 但是怎么说呢, 也有着各种的无奈与曲折, 面临这产品需求的不断变化和页面的不断更新, 对于一个程序员 ...

  5. LSI SAS 3008配置操作

    配置 LSI SAS 3008 介绍LSISAS3008的配置操作. 4.1 登录CU界面 介绍登录LSISAS3008的CU配置界面的方法. 4.2 创建RAID 介绍在LSISAS3008扣卡上创 ...

  6. params关键字载入空值的陷阱

    在编写方法时,不确定这个方法要传入多少个参数,或者随着程序的开发速度,该方法的参数会发生很大变化,在C#中引入了params关键字,使用params修饰object类型的数组并作为方法的参数类型,可以 ...

  7. 一小时搞定DIV+CSS布局-固定页面开度布局

    本文讲解使用DIV+CSS布局最基本的内容,读完本文你讲会使用DIV+CSS进行简单的页面布局. 转载请标明:http://www.kwstu.com/ArticleView/divcss_20139 ...

  8. C#生成高清缩略图

    /// <SUMMARY> /// 为图片生成缩略图 /// </SUMMARY> /// <PARAM name="phyPath">原图片的 ...

  9. Swift 流程控制

    import Foundation ...{ == { print(index) } } // 可选变量 类型后面加? var myName:String?="jikexueyuan&quo ...

  10. 树形dp hdu1561

    有的堡垒攻克需要攻克另一个堡垒,形成一个森林,最多攻克m个堡垒,求获得宝物的最大价值. 1,以0做根将森林形成树: 2,用背包计算当前节点下需要攻克k个堡垒能获得的宝物最大价值,但是注意同一个根节点的 ...