2016-02-15 14 views
8

Sono nuovo in Python e non ho trovato la risposta a questo. Facendo riferimento al codice alla fine del messaggio, posso sapere che cosa significa la parte "per articolo, totale in totals.items()" nella riga sottostante?AttributeError: l'oggetto 'dict' non ha attributo

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

Inoltre, il codice non è riuscita e ha detto

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

quando ho cambiato tutte le istanze di "item (s)" nel codice per "predittore (s)". Perchè è così?

# 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

Si prega di assicurarsi che il rientro è adatto in qualsiasi codice di pubblicare, in particolare codice Python, dal momento che il rientro influenza il comportamento di Python. – khelwood

+4

Penso che i downvoters siano un po 'approssimativi per i neofiti. – bgusach

+0

@bgusach: La mia _guess_ è che i downvotes sono dovuti alla mancanza di ricerche, dal momento che 'dict.items' è piuttosto facile da trovare nei documenti. OTOH, suppongo che i documenti Python ufficiali possano essere un po 'intimidatori se Python è il tuo primo linguaggio di programmazione, dal momento che sono rivolti a programmatori esperti. –

risposta

9

dict.items itera sulle coppie chiave-valore di un dizionario. Pertanto, for key, value in dictionary.items() si sovrapporrà ad ogni coppia. Si tratta di informazioni documentate e puoi verificarle nello official web page o, ancora più semplice, aprire una console python e digitare help(dict.items). Ed ora, tanto per fare un esempio:

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

Il AttributeError è un eccezione generata quando un oggetto non ha l'attributo che si è tentato di accedere. La classe dict non ha alcun attributo predictors (ora sai dove controllarlo :)), e quindi si lamenta quando provi ad accedervi. Facile come quello.

Ricordate sempre, RTFM: leggere il manuale "fine" :)

+0

Grazie mille per aver indicato la strada. Non avevo capito che totals.items si riferisce a dict.items e pensavo che fosse come un oggetto JSON di sorta. Ora so come affrontare questi problemi in futuro. Grazie ancora. –

+0

Felice di aiutare. Non dimenticare di contrassegnare la risposta come accettata! – bgusach

Problemi correlati