下面给出的代码有什么错误?

时间:2014-12-31 12:18:05

标签: python-2.7 machine-learning

我正在阅读编程集体智慧,并编写了以下代码但是执行它时出错了。

from pydelicious import get_popular,get_userposts,get_urlposts
import time

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

def fillItems(user_dict):
  all_items={}
  # Find links posted by all users
  for user in user_dict:
    for i in range(3):
      try:
        posts=get_userposts(user)
        break
      except:
        print "Failed user '+user+', retrying"
        time.sleep(4)
      try:
        for post in posts:
            url=post['href']
            user_dict[user][url]=1.0
            all_items[url]=1
      except:
        print 'No Posts'

  # Fill in missing items with 0
  for ratings in user_dict.values():
    for item in all_items:
      if item not in ratings:
        ratings[item]=0.0

我收到以下错误:

In [33]: fillItems(delusers)
Failed user ,retrying
Failed user ,retrying
Failed user ,retrying
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-33-ee215affceae> in <module>()
----> 1 fillItems(delusers)

C:\Users\Blue\Anaconda\deliciousrec.py in fillItems(user_dict)
     20         posts=get_userposts(user)
     21         break
---> 22       except:
     23         print "Failed user '+user+', retrying"
     24         time.sleep(4)

UnboundLocalError: local variable 'posts' referenced before assignment

1 个答案:

答案 0 :(得分:0)

在for循环中尝试3次后:

for i in range(3):
  try:
    posts=get_userposts(user)
    break
  except:
    print "Failed user '+user+', retrying"
    time.sleep(4)

(因为有:

Failed user ,retrying
Failed user ,retrying
Failed user ,retrying

posts未定义(因为get_userposts失败)。因此,posts中引用了局部变量for post in posts,但尚未分配。