-5

大家好,我是 python 语言的新手,我选择了以艰难的方式学习 python 来学习它并更好地理解......我对练习 25 感到困惑,当我们将代码直接导入终端时

>>> import ex25
>>> sentence = "All good things come to those who wait."
>>> words = ex25.break_words(sentence)

然后我得到一个属性错误

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'break_words'

我在 Windows 7 上使用 python 2.7 请帮助..... http://learnpythonthehardway.org/book/ex25.html

4

2 回答 2

3

在我看来,该练习并未指示学习者在导入之前保存文件。为了使其工作,您必须使用文本编辑器将定义 break_words 函数的代码保存在名为 ex25.py 的文件中。然后,从同一目录中通过键入以下命令打开 python 解释器:

python

并且您应该能够导入 ex25 并运行 ex25.py 模块定义的 break_words 函数。

于 2013-04-13T14:31:59.330 回答
2

您链接中的代码ex25.py确实包含该功能-您的代码并不表明您在将代码转录到文件中时以某种方式错过了它。检查您是否ex25.py包含页面中的所有代码,特别是包含此功能(它是最上面的):

def break_words(stuff):
    """This function will break up words for us."""
    words = stuff.split(' ')
    return words

考虑将代码粘贴到编辑器中而不是转录它,以避免出现此类错误。

于 2013-04-13T14:31:15.647 回答