码迷,mamicode.com
首页 > 编程语言 > 详细

笨方法学python Lesson 46 - 49

时间:2015-11-11 19:28:11      阅读:286      评论:0      收藏:0      [点我收藏+]

标签:

Exercises 46

代码

setup.py

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

config = {
    ‘description‘: ‘My Project‘,
    ‘author‘: ‘Jer‘,
    ‘url‘: ‘URL to get it at.‘,
    ‘download_url‘: ‘Where to download it.‘,
    ‘author_email‘: ‘hnyczhj@qq.com‘,
    ‘version‘: ‘0.1‘,
    ‘install_requires‘: [‘nose‘],
    ‘packages‘: [‘Jer‘],
    ‘scripts‘: [],
    ‘name‘: ‘projectname‘
}

setup(**config)

test.py

from nose.tools import *
import Jer

def setup():
    print "SETUP!"
    
def teardown():
    print "TEAR DOWN!"
    
def test_basic():
    print "I RAN!"

Notes

①本节主要是项目构建的基础知识

Exercise 47

game.py

class Room(object):
    
    def __init__(self, name, description):
        self.name = name
        self.description = description
        self.paths = {}
        
    def go(self, direction):
        return self.paths.get(direction, None)
        
    def add_paths(self, paths):
        self.paths.update(paths)

BLAH_tests.py

from nose.tools import *
from ex47.game import Room


def test_room():
    gold = Room("GoldRoom",
                """This room has gold in it you can grab. There‘s a
                door to the north.""")
    assert_equal(gold.name, "GoldRoom")
    assert_equal(gold.paths, {})
    
def test_room_paths():
    center = Room("Center", "Test room in the center")
    north = Room("North", "Test room in the north.")
    south = Room("South", "Test room in the south.")
    
    center.add_paths({‘north‘: north, ‘south‘: south})
    assert_equal(center.go(‘north‘), north)
    assert_equal(center.go(‘south‘), south)
    
def test_map():
    start = Room("Start", "You can go west and down a hole.")
    west = Room("Trees", "There are trees here, you can go east.")
    down = Room("Dungeon", "It‘s dark down here, you can go up.")
    
    start.add_paths({‘west‘: west, ‘down‘: down})
    west.add_paths({‘east‘: start})
    down.add_paths({‘up‘: start})
    
    assert_equal(start.go(‘west‘), west)
    assert_equal(start.go(‘west‘).go(‘east‘), start)
    assert_equal(start.go(‘down‘).go(‘up‘), start)

测试输出:

技术分享

①nosetests测试,自动化测试

Exercise 48

我的"扫描器"/lexicon.py

class Lexicon(object):
    
    def scan(self, stuff):
        self.stuff = stuff
        words = stuff.split()
        sentence = []
        for i in words:
            try:
                sentence.append((‘number‘, int(i)))
            except ValueError:
                if i in [‘north‘, ‘south‘, ‘east‘, ‘west‘, ‘down‘, ‘up‘, ‘left‘, ‘right‘, ‘back‘]:
                    sentence.append((‘direction‘, i))
                elif i in [‘go‘, ‘stop‘, ‘kill‘, ‘eat‘]:
                    sentence.append((‘verb‘, i))
                elif i in [‘the‘, ‘in‘, ‘of‘, ‘from‘, ‘at‘, ‘in‘]:
                    sentence.append((‘stop‘, i))
                elif i in [‘door‘, ‘bear‘, ‘princess‘, ‘cabinet‘]:
                    sentence.append((‘noun‘, i))
                else:
                    sentence.append((‘error‘, i))

        return sentence
       
lexicon = Lexicon()

测试代码 lexicon_tests.py

from nose.tools import *
from ex48.lexicon 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("ASDFASDFASDF"), [(‘error‘, ‘ASDFASDFASDF‘)])
    result = lexicon.scan("bear IAS princess")
    assert_equal(result, [(‘noun‘, ‘bear‘),
                          (‘error‘, ‘IAS‘),
                          (‘noun‘, ‘princess‘)])

输出

技术分享

Notes:

①试了半天,一直提示

unbound method must be called with instance as first argument

这个错误,最后在lexicon.py中加了一个实例化语句,最终解决

②加分习题3,识别大小写用lower()全部转换成小写再判断即可

③加分习题4,另外一种方式就是try里对字符串进行操作,except里对数字进行操作。

try:
    i.lower()
    pass
except SyntaxError:
    pass

Exercise 49









笨方法学python Lesson 46 - 49

标签:

原文地址:http://my.oschina.net/u/2297516/blog/529054

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!