2017-01-31 99 views
1

我試圖執行此代碼,顯示我一些IMDB電影分級:格式字符串時數項丟失

import json 
import sys 

import imdb 
import sendgrid 

NOTIFY_ABOVE_RATING = 7.5 

SENDGRID_API_KEY = "API KEY GOES HERE" 


def run_checker(scraped_movies): 
    imdb_conn = imdb.IMDb() 
    good_movies = [] 
    for scraped_movie in scraped_movies: 
     imdb_movie = get_imdb_movie(imdb_conn, scraped_movie['name']) 
     if imdb_movie['rating'] > NOTIFY_ABOVE_RATING: 
      good_movies.append(imdb_movie) 
    if good_movies: 
     send_email(good_movies) 


def get_imdb_movie(imdb_conn, movie_name): 
    results = imdb_conn.search_movie(movie_name) 
    movie = results[0] 
    imdb_conn.update(movie) 
    print("{title} => {rating}".format(**movie)) 
    return movie 


def send_email(movies): 
    sendgrid_client = sendgrid.SendGridClient(SENDGRID_API_KEY) 
    message = sendgrid.Mail() 
    message.add_to("[email protected]") 
    message.set_from("no-reply[email protected]") 
    message.set_subject("Highly rated movies of the day") 
    body = "High rated today:<br><br>" 
    for movie in movies: 
     body += "{title} => {rating}".format(**movie) 
    message.set_html(body) 
    sendgrid_client.send(message) 
    print("Sent email with {} movie(s).".format(len(movies))) 


if __name__ == '__main__': 
    movies_json_file = sys.argv[1] 
    with open(movies_json_file) as scraped_movies_file: 
     movies = json.loads(scraped_movies_file.read()) 
    run_checker(movies) 

但它返回我這個錯誤:

C:\Python27\Scripts>python check_imdb.py movies.json 
T2 Trainspotting => 8.1 
Sing => 7.3 
Traceback (most recent call last): 
    File "check_imdb.py", line 49, in <module> 
    run_checker(movies) 
    File "check_imdb.py", line 16, in run_checker 
    imdb_movie = get_imdb_movie(imdb_conn, scraped_movie['name']) 
    File "check_imdb.py", line 27, in get_imdb_movie 
    print("{title} => {rating}".format(**movie)) 
KeyError: 'rating' 

發生這種情況是因爲它試圖打印沒有評分的電影。 我嘗試過/多次修復它,但沒有成功。

回答

0

問題是因爲您的movie字典沒有rating密鑰。爲了解決這個問題,你可以使用dict.setdefault爲「未知」或「0」 (基於什麼適合你)作爲設定等級的默認值:

# set value of 'rating' as 'unknown' if 'rating' key is not present 
movie.setdefault('rating', 'unknown') 

# then do format as: 
"{title} => {rating}".format(**movie) 

欲瞭解更多信息,請查看:Use cases for the setdefault dict method

+0

我做到了。但現在,當沒有標題時,它顯示 'movie = results [0]' 'IndexError:list index out of range' Tryed movie.setdefault('title','unknown')but nothing chaged。 – Lestat

+0

@Lestat我相信你知道這不是教程服務。你將不得不花費一些努力來自己調試問題。基於這個新錯誤,最大I(或其他人)可以告訴'結果'是空列表,並且您試圖訪問第0個索引處的元素。因此,你在錯誤中看到的消息 –