我是Python的新手,正在通过“学习Python艰难之路”网络教程。但是由于传递单个字符串存在问题,我已经停止了。我能够通过一个清单确定......
练习48让我们对单元测试中的代码进行逆向工程。单元测试是:
def test_directions():
assert_equal(Lexicon.scan("north"), [('direction', 'north')])
我的代码如下所示:
class Lexicon:
def __init__(self):
self.directions = ['north','south','east','west','down','up','left','right','back']
self.verbs = ['go','stop','kill','eat']
self.stops = ['the','in','of','from','at','it']
self.nouns = ['door','bear','princess','cabinet']
def scan(self, words):
result = []
for i in words:
if i in self.directions:
result.append( ('direction', i) )
elif i in self.verbs:
result.append( ('verb', i) )
elif i in self.stops:
result.append( ('stop', i) )
elif i in self.nouns:
result.append( ('noun', i) )
else:
try:
result.append( ('number', int(i)) )
except ValueError:
result.append( ('error', i) )
return result
从python提示符运行代码会给我以下结果:
>>> from lexicon import Lexicon
>>> test = Lexicon()
>>> test.directions
['north', 'south', 'east', 'west', 'down', 'up', 'left', 'right', 'back']
>>> words = ['south']
>>> test.scan(words)
[('direction', 'south')]
>>>
>>> test.scan("north")
[('error', 'n'), ('error', 'o'), ('error', 'r'), ('error', 't'), ('error', 'h')]
>>>
如果有人能够指出为什么列表与单个字符串的区别对待,我将非常感激?还有我如何重新编写代码以便两者都以同样的方式处理?
先谢谢,奈杰尔。
答案 0 :(得分:1)
这一行试图遍历单词列表
for i in words:
如果您只是传入一个字符串,i
实际上会接受每个字母,例如
for i in 'test':
print i
t
e
s
t
要传入一个单词,请传入list
长度为1。
test.scan(["north"])
答案 1 :(得分:0)
您的功能不适用于单个字符串。会发生什么是for i in words:
迭代字符串的字符。
可以更改函数,使其适用于单个字符串和字符串的可迭代。但是,总是传递iteratables并且不打扰单个字符串会更加一致。
要传递单个字符串,只需传递一个元素列表(["north"]
)或元组(("north",)
)。
答案 2 :(得分:0)
def scan(self, words):
result = []
words = words.split()
for i in words:
...
练习中的unittest可以看作 blackbox 规范,用于调用该方法。您的方法必须符合该规范。
要考虑可能包含多个以空格分隔的单词的字符串参数,split
字符串。 split
会返回list
,这将适用于该方法的其余部分。