python: 第一次for循环后无法访问urllib对象

python: urllib object cannot be accessed after the first for loop

以下代码无法正常工作,因为 'line1' 不存在。但是,'line' 确实存在。似乎 'fhand' 在第一个 for 循环之后改变了。如果我们注释掉第一个 for 循环,那么代码运行得很好。

谁能解释为什么会这样?

import urllib
fhand = urllib.urlopen('http://www.py4inf.com/code/romeo.txt')

# It is the following 2 lines that cause error
for line in fhand:
    print line.strip()

counts = dict()
for line1 in fhand:
    words = line1.split()

    for word in words:
        counts[word] = counts.get(word, 0) + 1

print counts

urllib.urlopen returns一个generetor,第一个循环就耗尽了

fhand转换为列表
(fhand = list(urllib.urlopen('http://www.py4inf.com/code/romeo.txt'))),或在第一个循环内执行所有操作(即只有一个循环)。