2016-02-15 26 views
8

Tôi mới dùng python và không thể tìm thấy câu trả lời cho điều này. Đề cập đến mã ở cuối thông báo, tôi có thể biết phần "cho mục, tổng số trong tổng số .tems()" trong dòng dưới đây có nghĩa là gì?AttributeError: đối tượng 'dict' không có thuộc tính

rankings = [(total/simSums[item], item) for item, total in totals.items()] 

Ngoài ra, mã thất bại và nói

AttributeError: 'dict' object has no attribute 'predictors' 

khi tôi thay đổi tất cả các trường hợp của "mục (s)" trong mã để "dự đoán (s)". Tại sao vậy?

# Return the Pearson correlation coefficient for p1 and p2 
def sim_person(prefs, p1, p2): 
    # Get the list of shared_items 
    si={} 
    for item in prefs[p1]: 
     if item in prefs[p2]:si[item]=1 

    # Find the number of elements 
    n=len(si) 

    # if they have no ratings in common, return 0 
    if n==0: return 0 

    # Add up all the preferences 
    sum1 = sum([prefs[p1][it] for it in si]) 
    sum2 = sum([prefs[p2][it] for it in si]) 

    # Sum up the squares 
    sum1Sq = sum([pow(prefs[p1][it],2) for it in si]) 
    sum2Sq = sum([pow(prefs[p2][it],2) for it in si]) 

    # Sum up the products 
    pSum = sum([prefs[p1][it]*prefs[p2][it] for it in si]) 

    # Calculate Person score 
    num = pSum - (sum1*sum2/n) 
    den = sqrt((sum1Sq - pow(sum1,2)/n)*(sum2Sq - pow(sum2,2)/n)) 
    if den == 0: return 0 

    r = num/den 
    return r 

# Returns the best matches for person from the prefs dictionary. 
# Number of results and similarity function are optional params. 
def topMatch(prefs, person, n=5, similarity=sim_person): 
    scores = [(similarity(prefs, person, other), other) 
       for other in prefs if other!=person] 

    # Sort the list so the highest scores appear at the top 
    scores.sort() 
    scores.reverse() 
    return scores[0:n] 

# Gets recommendations for a person by using a weighted average 
# of every other user's rankings 
def getRecommendations(prefs, person, similarity=sim_person): 
    totals = {} 
    simSums = {} 
    for other in prefs: 
     # don't compare me to myself 
     if other == person: continue 
     sim = similarity(prefs, person, other) 

     # ignore scores of zero of lower 
     if sim<=0: continue 
     for item in prefs[other]: 

      # only score movies I haven't seen yet 
      if item not in prefs[person] or prefs[person][item]==0: 
       # Similarity * Score 
       totals.setdefault(item, 0) 
       totals[item]+=prefs[other][item]*sim 
       # Sum of similarities 
       simSums.setdefault(item, 0) 
       simSums[item]+=sim 

    # Create the normalized list 
    rankings = [(total/simSums[item], item) for item, total in totals.items()] 

    # Return the sorted list 
    rankings.sort() 
    rankings.reverse() 
    return rankings 
+2

Hãy chắc chắn rằng thụt đầu dòng là thích hợp trong bất kỳ mã bạn đăng, đặc biệt là mã Python, vì thụt đầu dòng ảnh hưởng đến hành vi của Python. – khelwood

+4

Tôi nghĩ rằng bạn downvoters là một chút thô trên người mới. – bgusach

+0

@bgusach: My _guess_ là downvotes là do thiếu nghiên cứu, vì 'dict.items' khá dễ tìm trong tài liệu. OTOH, tôi cho rằng các tài liệu Python chính thức có thể hơi đáng sợ nếu Python là ngôn ngữ lập trình đầu tiên của bạn, vì chúng là nhằm vào các lập trình viên dày dạn kinh nghiệm. –

Trả lời

9

Lặp lại các cặp khóa-giá trị của từ điển. Do đó for key, value in dictionary.items() sẽ lặp qua mỗi cặp. Đây là thông tin được ghi lại và bạn có thể kiểm tra nó trong official web page hoặc thậm chí dễ dàng hơn, mở bảng điều khiển python và nhập help(dict.items). Và bây giờ, cũng giống như một ví dụ:

>>> d = {'hello': 34, 'world': 2999} 
>>> for key, value in d.items(): 
... print key, value 
... 
world 2999 
hello 34 

AttributeError là một ngoại lệ được ném khi một đối tượng không có thuộc tính bạn cố truy cập. Lớp dict không có bất kỳ thuộc tính predictors (bây giờ bạn biết nơi để kiểm tra nó :)), và do đó nó than phiền khi bạn cố gắng truy cập nó. Dễ dàng như vậy.

Luôn luôn nhớ, RTFM: đọc "tốt" bằng tay :)

+0

Cảm ơn rất nhiều vì đã chỉ đường. Tôi đã không nhận ra rằng totals.items đề cập đến dict.items và nghĩ nó giống như một đối tượng JSON. Bây giờ tôi biết cách tiếp cận những vấn đề như vậy trong tương lai. Cảm ơn một lần nữa. –

+0

Rất vui được trợ giúp. Đừng quên đánh dấu câu trả lời là đã được chấp nhận! – bgusach

Các vấn đề liên quan