正如标题所示,我正在做一个教程。但是我遇到了这个错误:
>>> from words import (fetch_words, print_words)
>>> print_words(fetch_words())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\jjosey\Documents\pyfund\words.py", line 12, in print_words
for word in story_words:
TypeError: 'NoneType' object is not iterable
调用此文件时(words.py):
from urllib.request import urlopen
def fetch_words():
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)
def print_words(story_words):
for word in story_words:
print(word)
def main():
words = fetch_words()
print_words(words)
if __name__ == '__main__':
main()
我理解错误表明我正在调用空数组。但这正是导师在视频中的作用,所以我假设我在某个地方犯了一个错误,导致错误袭击了我。这是我学习Python的第一天,所以我没有发现它。
任何帮助表示赞赏。感谢
答案 0 :(得分:4)
尝试在fetch_words
末尾添加words = fetch_words()
语句。如果没有它,words
将导致None
成为def fetch_words():
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)
return story_words
。
<module>
答案 1 :(得分:0)
def fetch_words():
with urlopen('http://sixty-north.com/c/t.txt') as story:
story_words = []
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)
此函数有一个错误...虽然您稍后尝试使用返回的值,但它不会return
一个值。试试这个......
def fetch_words():
story_words = []
with urlopen('http://sixty-north.com/c/t.txt') as story:
for line in story:
line_words = line.decode('utf-8').split()
for word in line_words:
story_words.append(word)
return story_words