Untitled
unknown
python
a year ago
4.1 kB
11
Indexable
import json
import os
# File paths
movies_file = "movies.json"
user_preferences_file = "user_preferences.json"
# Sample movie dataset
movies = [
{"id": 1, "title": "The Shawshank Redemption", "genres": ["Drama"]},
{"id": 2, "title": "The Godfather", "genres": ["Crime", "Drama"]},
{"id": 3, "title": "The Dark Knight", "genres": ["Action", "Crime", "Drama"]},
{"id": 4, "title": "Pulp Fiction", "genres": ["Crime", "Drama"]},
{"id": 5, "title": "Forrest Gump", "genres": ["Drama", "Romance"]},
{"id": 6, "title": "Inception", "genres": ["Action", "Adventure", "Sci-Fi"]},
{"id": 7, "title": "The Matrix", "genres": ["Action", "Sci-Fi"]},
{"id": 8, "title": "Interstellar", "genres": ["Adventure", "Drama", "Sci-Fi"]}
]
# Creating JSON Files and adding content
def initialize_files():
if not os.path.exists(user_preferences_file):
with open(user_preferences_file, "w") as file:
json.dump({}, file, indent=4)
if not os.path.exists(movies_file):
with open(movies_file, "w") as file:
json.dump(movies, file, indent=4)
def load_movies():
try:
with open(movies_file, "r") as file:
return json.load(file)
except json.JSONDecodeError:
print("Error: Movies file is corrupted or empty.")
return []
except FileNotFoundError:
return []
def load_user_preferences() -> dict:
try:
with open(user_preferences_file, "r") as file:
return json.load(file)
except json.JSONDecodeError:
print("Error: User preferences file is corrupted or empty.")
return {}
except FileNotFoundError:
return {}
def save_user_preferences(preferences: dict):
try:
# Convert sets to lists for JSON serialization
preferences_serializable = {k: list(v) for k, v in preferences.items()}
with open(user_preferences_file, "w") as file:
json.dump(preferences_serializable, file, indent=4)
except IOError as e:
print(f"Error saving user preferences: {e}")
def recommend_movies(user_id: str) -> list:
user_preferences = load_user_preferences()
user_genres = set(user_preferences.get(user_id, []))
if not user_genres:
return ["No preferences found. Please set your preferences first."]
recommended_movies = []
for movie in load_movies():
movie_genres = set(movie["genres"])
# Recommend movie if it has any genre in common with the user's preferences
if user_genres.intersection(movie_genres):
recommended_movies.append(movie["title"])
return recommended_movies if recommended_movies else ["No recommendations found."]
def update_user_preferences(user_id: str, genres: list):
"""Update user preferences."""
user_preferences = load_user_preferences()
user_preferences[user_id] = set(genres)
save_user_preferences(user_preferences)
def main():
initialize_files()
while True:
print("\nMovie Recommendation System")
print("1. Set preferences")
print("2. Get recommendations")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == "1":
user_id = input("Enter your user ID: ")
genres = input("Enter your preferred genres (comma separated): ").split(",")
genres = [genre.strip() for genre in genres]
update_user_preferences(user_id, genres)
print("Preferences updated.")
elif choice == "2":
user_id = input("Enter your user ID: ")
recommendations = recommend_movies(user_id)
print("\nRecommended Movies:")
for movie in recommendations:
print(f"- {movie}")
elif choice == "3":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
Editor is loading...
Leave a Comment