2016-07-09 62 views
0

由於'line1'不存在,下列代碼無法正常工作。但是,'線'確實存在。看起來'fhand'在第一個for循環後發生了變化。如果我們註釋掉第一個for循環,那麼代碼運行得很好。python:在第一個for循環後無法訪問urllib對象

任何人都可以解釋爲什麼發生這種情況?

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 
+0

第一次通過'fhand'循環_consumes_數據,所以沒有剩下的第二個循環。如果您想多次循環訪問,請製作自己的數據副本並循環訪問。 –

+0

根據您的評論,我找到了詳細解釋「類文件對象」行爲的文章。希望這會幫助其他人:http://joseph-long.com/writing/file-like-objects-in-python/ –

回答

0

urllib.urlopen返回generetor,這是由第一回路排出。

要麼轉換fhand到一個列表
fhand = list(urllib.urlopen('http://www.py4inf.com/code/romeo.txt'))),或做的第一循環中的一切(即只有一個循環)。