Python与集体智能 KeyError:href

0 投票
2 回答
1358 浏览
提问于 2025-04-18 08:50

我现在正在尝试一本叫做《编程集体智慧》的书里的代码,但遇到了一个错误,是由pydelicious.py这个文件引起的。有没有人能告诉我怎么调试这种问题呢?

Python代码:

def initializeUserDict(tag, count = 5):
user_dict = {}

#get the top count' popular posts
for p1 in get_popular(tag = tag)[0:count]:
    #find all users who posted this
    for p2 in get_urlposts(p1['href']):
        user = p2['user']
        user_dict[user] = {}
return user_dict

错误信息:

>>>from deliciousrec import *
>>>delusers = initializeUserDict('programming')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "deliciousrec.py", line 9, in initializeUserDict
for p2 in get_urlposts(p1['href']): 
KeyError: 'href'

p1:

for p1 in get_popular(tag = 'python')[0:5]:
   print p1

{'extended': u'', 'description': u'20.19. SimpleHTTPServer \u2014 Simple HTTP request      handler \u2014 Python v2.7.7 documentation', 'tags': u'http', 'url': u'https://docs.python.org/2/library/simplehttpserver.html', 'user': u'', 'dt': ''}
{'extended': u'', 'description': u'Must Have Python Packages | Algorithm.co.il', 'tags': u'python', 'url': u'http://www.algorithm.co.il/blogs/programming/must-have-python-packages/', 'user': u'', 'dt': ''}
{'extended': u'', 'description': u'Le blog de Thomas Blanchard: Configure pydistutils.cfg - example python distutils config file', 'tags': u'distutils', 'url': u'http://bouktin.blogspot.be/2012/04/configure-pydistutilscfg-python.html', 'user': u'', 'dt': ''}
{'extended': u'', 'description': u'3.2 Installation', 'tags': u'cheetah', 'url': u'http://www.cheetahtemplate.org/docs/users_guide_html_multipage/gettingStarted.install.html', 'user': u'', 'dt': ''}
{'extended': u'', 'description': u"How can I represent an 'Enum' in Python? - Stack Overflow", 'tags': u'enum', 'url': u'http://stackoverflow.com/questions/36932/how-can-i-represent-an-enum-in-python?rq=1', 'user': u'', 'dt': ''}

2 个回答

0

你从 get_popular() 得到的 p1 似乎没有和 'href' 这个键关联的值。你应该检查一下 p1 是否包含这个键,或者把 for p2 in get_urlposts(p1['href']) 这一部分放在一个尝试-捕获的结构里。

2

别再用“href”了,你需要把“href”换成“url”

def initializeUserDict(tag, count=5):
    user_dict = {}
    # get the top count' popular posts
    for p1 in get_popular(tag=tag)[0:count]:
    # find all users who posted this
        for p2 in get_urlposts(p1['url']):  #<----------------HERE, I changed href by url
            user = p2['user']
            user_dict[user] = {}
    return user_dict

祝好

撰写回答