Instant Movie Match Using Python

Instant Movie Match Using Python

Hello, Pythonistas! Welcome back.

Ever spent way too much time searching for movie details before deciding what to watch?

Well, I’ve got something that can save you from all that hassle!

Just enter the movie name, and based on your taste and the movie’s genre, it will tell you if it’s worth your time.

Plus, you’ll get all the details you need to make an informed decision.

Let’s dive into it!

Initialize IMDB Instance

First, we import in the imdb library to use its features.

We created something called ia that lets us talk to IMDb (an online movie ratings website) and ask for movie information.

import imdb

# Initialize IMDb instance
ia = imdb.Cinemagoer()

Get The Movie Name from the User

We ask the user to type in the name of a movie.

The .strip() part removes any extra spaces from the name.

If the user doesn’t type anything, we tell them they must enter a name, and then we stop the program.

# Get movie name from user
movie_name = input("Enter a movie name: ").strip()
if not movie_name:
    print("You must enter a movie name!")
    exit()

Search for the Movie And Check if There are any Results

We search IMDb for movies that match the name the user typed.

If no movies are found, we tell the user and stop the program.

# Search for the movie
items = ia.search_movie(movie_name)

# Check if there are any search results
if not items:
    print("No results found.")
    exit()

Display Search Results

We show a list of movies that match the name the user typed.

For each movie, we show its title and the year it was released.

If the year is missing, we show “N/A” (not available) instead.

# Display search results
print("\nSearch Results:")
for index, movie in enumerate(items, start=1):
    title = movie.get('title', 'N/A')
    year = movie.get('year', 'N/A')
    print(f"{index}. {title} ({year})")

Get The User’s Choice

We ask the user to pick one of the movies from the list by entering its number.

We check if the number they enter is valid (e.g., within the list).

If the number is not valid, we show an error and stop the program.

# Get the user's choice
try:
    movie_index = int(input("\nEnter the number of the movie you want to get info for: ")) - 1
    if movie_index not in range(len(items)):
        raise ValueError("Invalid selection.")
except ValueError as e:
    print(f"Error: {e}")
    exit()

Fetch and Display movie information

We find more detailed information about the movie the user chose.

Then, we show this information, including the title, year, IMDb rating, genres, directors, main cast members, plot, runtime, country, and language.

If any information is missing, we show “N/A” instead.

# Fetch movie information
movie_id = items[movie_index].movieID
movie_info = ia.get_movie(movie_id)

# Display movie information
print("\nMovie Information:")
print(f"Title: {movie_info.get('title', 'N/A')}")
print(f"Year: {movie_info.get('year', 'N/A')}")
print(f"IMDB Rating: {movie_info.get('rating', 'N/A')}")
print(f"Genres: {', '.join(movie_info.get('genres', ['N/A']))}")
print(f"Director(s): {', '.join(str(d) for d in movie_info.get('directors', []))}")
print(f"Cast: {', '.join(str(c) for c in movie_info.get('cast', [])[:5])}...") 
print(f"Plot: {movie_info.get('plot outline', 'N/A')}")
print(f"Runtime: {movie_info.get('runtimes', ['N/A'])[0]} minutes")
print(f"Country: {', '.join(movie_info.get('countries', ['N/A']))}")
print(f"Language: {', '.join(movie_info.get('languages', ['N/A']))}")

Suggest If The Movie is “Worth Watching” Based on Genre Preference

# Suggest if the movie is worth watching based on genre preference
preferred_genre = input("\nEnter your preferred genre: ").strip().capitalize()
if preferred_genre in movie_info.get('genres', []):
    print(f"\nGreat! '{movie_info.get('title')}' is a {preferred_genre} movie, so it might be a good choice for you!")
else:
    print(f"\nHmm, '{movie_info.get('title')}' might not be your cup of tea since it's not a {preferred_genre} movie.")

Sample Output

Click to view sample output
Enter a movie name: red notice

Search Results:
1. Red Notice (2021)
2. SAS: Red Notice (2021)
3. Red Notice 2 (N/A)
4. Red Notice (N/A)
5. Red Notice (2011)
6. SAS: Red Notice 2 (N/A)
7. Red Notice - Untrustworthy Spoilers (2021)
8. Red Notice: Forensic Sketches (2021)
9. Badshah, DIVINE, Jonita Gandhi, Mikey McCleary: Bach Ke Rehna (Red Notice) (2021)
10. Red Notice (2021)
11. Red Notice (2022)
12. Red Notice (2021)
13. Red Notice (2021)
14. Red Notice (2021)
15. Red Notice (2021)
16. Red Notice (2021)
17. Red Notice (2022)
18. 'Red Notice' (2021)
19. Red Notice (2021) (2021)
20. Red Notice Review (2021)

Enter the number of the movie you want to get info for: 1

Movie Information:
Title: Red Notice
Year: 2021
IMDB Rating: 6.3
Genres: Action, Comedy, Thriller
Director(s): Rawson Marshall Thurber
Cast: Dwayne Johnson, Ryan Reynolds, Gal Gadot, Ritu Arya, Chris Diamantopoulos...
Plot: When an Interpol-issued Red Notice--the highest-level warrant to hunt and capture the world's most wanted--goes out, the FBI's top profiler, John Hartley (Dwayne Johnson), is on the case. His global pursuit lands him smack-dab in the middle of a daring heist where he's forced to partner with the world's greatest art thief, Nolan Booth (Ryan Reynolds), in order to catch the world's most wanted art thief, "The Bishop" (Gal Gadot). The high-flying adventure that ensues takes the trio around the world, across the dance floor, trapped in a secluded prison, into the jungle and, worst of all for them, constantly into one another's company.
Runtime: 118 minutes
Country: United States, United Kingdom, Singapore, Italy, Thailand, Canada
Language: English, Russian, Italian, Spanish, Indonesian

Enter your preferred genre: Action

Great! 'Red Notice' is a Action movie, so it might be a good choice for you!

Full Source Code: Instant Movie Match Using Python

Click for the full source code of Instant Movie Match Using Python
import imdb

# Initialize IMDb instance
ia = imdb.Cinemagoer()

# Get movie name from user
movie_name = input("Enter a movie name: ").strip()
if not movie_name:
    print("You must enter a movie name!")
    exit()

# Search for the movie
items = ia.search_movie(movie_name)

# Check if there are any search results
if not items:
    print("No results found.")
    exit()

# Display search results
print("\nSearch Results:")
for index, movie in enumerate(items, start=1):
    title = movie.get('title', 'N/A')
    year = movie.get('year', 'N/A')
    print(f"{index}. {title} ({year})")

# Get the user's choice
try:
    movie_index = int(input("\nEnter the number of the movie you want to get info for: ")) - 1
    if movie_index not in range(len(items)):
        raise ValueError("Invalid selection.")
except ValueError as e:
    print(f"Error: {e}")
    exit()

# Fetch movie information
movie_id = items[movie_index].movieID
movie_info = ia.get_movie(movie_id)

# Display movie information
print("\nMovie Information:")
print(f"Title: {movie_info.get('title', 'N/A')}")
print(f"Year: {movie_info.get('year', 'N/A')}")
print(f"IMDB Rating: {movie_info.get('rating', 'N/A')}")
print(f"Genres: {', '.join(movie_info.get('genres', ['N/A']))}")
print(f"Director(s): {', '.join(str(d) for d in movie_info.get('directors', []))}")
print(f"Cast: {', '.join(str(c) for c in movie_info.get('cast', [])[:5])}...") 
print(f"Plot: {movie_info.get('plot outline', 'N/A')}")
print(f"Runtime: {movie_info.get('runtimes', ['N/A'])[0]} minutes")
print(f"Country: {', '.join(movie_info.get('countries', ['N/A']))}")
print(f"Language: {', '.join(movie_info.get('languages', ['N/A']))}")

# Suggest if the movie is worth watching based on genre preference
preferred_genre = input("\nEnter your preferred genre: ").strip().capitalize()
if preferred_genre in movie_info.get('genres', []):
    print(f"\nGreat! '{movie_info.get('title')}' is a {preferred_genre} movie, so it might be a good choice for you!")
else:
    print(f"\nHmm, '{movie_info.get('title')}' might not be your cup of tea since it's not a {preferred_genre} movie.")

Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python Instant Movie Match Using Python

Leave a Reply