How to check if input in the list

Viewed 63

I am trying to build a suggestion tool based on a movie dataset. More specifically it will suggest a movie by title based on genre keyword.

But I couldn't pass the loop/check part of the script, here is what I have tried:

import nltk
import pandas as pd
from nltk.tokenize import word_tokenize
import random

#CSV READ & GENRE-TITLE
data = pd.read_csv("data.csv")

df_title = data["title"]
df_genre = data["genre"]

#TOKENIZE
tokenized_genre = [word_tokenize(i) for i in df_genre]

choice = {}

while choice != "exit":
    choice = input("Please enter a word = ")
    for word in {choice}:
        if word in df_genre:
            """The random title of the random adventure movie will be implemented here"""  
        else:
            print("The movie of the genre doesn't exist")

The output of the tokenized_genre like this:

[['Biography', ',', 'Crime', ',', 'Drama'],
 ['Drama'], ['Drama', ',', 'History'],
 ['Adventure', ',', 'Drama', ',', 'Fantasy'],
 ['Biography', ',', 'Drama'],
 ['Biography', ',', 'Drama', ',', 'Romance']

The output of the loop:

Please enter a word = adventure
The movie of the genre doesn't exist
Please enter a word = Adventure
The movie of the genre doesn't exist

I guess the mistake in the list of the tokenized words but I couldn't solve it.

2 Answers

you may use:

search = {e.lower() for l in tokenized_genre  for e in l}
choice = input("Please enter a word = ")
while choice != "exit":
    if choice.lower() in search:
        # TODO: The random title of the random adventure movie will be implemented here
         print("Works!")  
    else:
        print("The movie of the genre doesn't exist")
    choice = input("Please enter a word = ")

search is a set containing all your words from tokenized_genre only once, the benefit is that the search in a set is O(1) time complexity also since your choice variable is a word you could check dirctly if the input word is in the search set

Maybe I'm wrong, I'm not a Python master.

It seems that df_genre returns a "list of list" not a list. You should join the lists and then search there.

import itertools

df_genre = [['Biography', ',', 'Crime', ',', 'Drama'], ['Drama'], ['Drama', ',', 'History'], ['Adventure', ',', 'Drama', ',', 'Fantasy'], ['Biography', ',', 'Drama'], ['Biography', ',', 'Drama', ',', 'Romance']]

#TOKENIZE
joined_list = list(itertools.chain.from_iterable(df_genre))

choice = {}

while choice != "exit":
    choice = input("Please enter a word = ")
    for word in {choice}:
        if word in joined_list:
            """The random title of the random adventure movie will be implemented here"""  
            print("Works!")
        else:
            print("The movie of the genre doesn't exist")

Result of local test

I don't know if it is what you are looking for. Hope it helps.

Related