我是编程领域的新手,学习用Python编写代码下面的测试代码给了我尝试编写模块本身的问题,请对如何编写它的任何帮助将非常感谢。
from nose.tools import *
from glass import moviy
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')])发布于 2014-10-24 04:54:57
你有一个黑匣子,通过输入,你必须发现它里面有什么。
这是TDD背后的基本思想
就像Ignacio说的,你可以用字典。它将通过测试。但这并不是一个非常有用的实现,因为你不可能有一个键用于所有的数字,例如。它会起作用的。但在现实生活中行不通。
根据您的测试,您有一个词典对象。
class Lexicon(object):
def __init__(self):
pass
def scan(self, inputStr):您会注意到,所有返回都是元组的向量。每个元组都是输入字符串中的单词。所以你可以假设它是被空间分割的。
tokens = inputStr.split(" ")创建一个向量来保存答案:
answers = []您可以开始猜测每个令牌的值。
for token in tokens:如果它是一个数字,让我们先试一试。
try:
answers.append(("number", int(token)))
except:
pass最后你会返回答案
return answers在此之后,您可以运行数字测试:
lexicon = Lexicon()
test_numbers()并且不会发生错误。
在此之后,您可以测试列表中的字符串。首先在对象中创建列表。
class Lexicon(object):
directions = [ "north", "south", "east", "west"]
def __init__(self):
...在扫描功能中,您可以测试令牌是否在方向列表中。
...
pass
if token in self.directions:
answers.append(("direction",token))现在运行:
lexicon = Lexicon()
test_numbers()
test_directions()并且不会发生错误!这个想法与其他价值观类似。
顺便说一下。如果你没有像class,tuple,dict这样的概念。我建议你在here上看看
https://stackoverflow.com/questions/26535561
复制相似问题