【发布时间】:2016-02-11 03:23:29
【问题描述】:
我想统计一个特定 url 中的所有单词
import urllib.request
url = 'http://www.py4inf.com/code/romeo.txt'
fhand = urllib.request.Request(url)
resp = urllib.request.urlopen(fhand)
counts = dict()
for line in resp:
words = line.split()
print (words)
for word in words:
counts[word] = counts[word] +1
print (counts)
运行此程序时出现错误: [b'But', b'soft', b'what', b'light', b'through', b'yonder', b'window', b'breaks']
Traceback(最近一次调用最后一次): 文件“C:/Python/Hello/Exercise.py”,第 13 行,在 计数[字] = 计数[字] +1
KeyError: b'But'
为什么每个单词或每一行都附加 b'?如果我使用相同的代码从文件中读取,它工作正常。
【问题讨论】: