Python Forum
Help printing any items that contains a keyword from a list
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help printing any items that contains a keyword from a list
#1
Hey everybody really appreciate the help lately however I am stuck on something that might be rather simple and I am missing the point.
I need to print all items that contain a user defined keyword from a list

I can get it to print where the index locations are just not the actual titles
selection = input("Please Select:")
if selection =='s':
    list = movies_list
    string = str(input("Search keyword: "))
    print (string)
if any(string in s for s in list):
    print ("Yes")
else:
    print("Not found")
Reply
#2
You have condition for s in list, which generates a bunch of Trues and Falses. Changing that to s for s in list if condition will generate the actual matching values.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(May-06-2017, 01:28 AM)ichabod801 Wrote: You have condition for s in list, which generates a bunch of Trues and Falses. Changing that to s for s in list if condition will generate the actual matching values.

Ok so I kinda get what you mean. Now I can print the list if it contains a matching keyword and in turn if it doesnt contain a matching keyword it will print ("unknown command") But instead of printing the matching titles to the keyword

e.g
Keyword = Dead
output

Dawn of the Dead, Land Of The Dead , Dead Calm etc etc

It just prints the whole txt file list of titles

selection = input("Please Select:")
if selection =='s':
    list = movies_list
    keyword = str(input("Search keyword: "))
    print (keyword)
if any(keyword for s in list):
    for keyword in list:
        print(keyword)
else:
    print("Unknown Command")
Reply
#4
if any(keyword for s in list):
Will just return True if keyword is in list.
>>> keyword = 'Fi'
>>> movie_list = ['Pulp Fiction', 'Fight Club', 'The Matrix', 'The Godfather']
>>> any(keyword for s in movie_list)
True
Don't use list as variable name,name it used bye Python.
Here you just itertate over list,make no sense as you have used keyword as a variable before.
Now it's just a temporary variable in the loop.
for keyword in list:
    print(keyword)
Just to show something that dos the same:
for rubberduck in list:
    print(rubberduck)
Some hints:
>>> keyword = 'Fi'
>>> movie_list = ['Pulp Fiction', 'Fight Club', 'The Matrix', 'The Godfather']
>>> for movie in movie_list:
...     if keyword in movie:
...         print(movie)
       
Pulp Fiction
Fight Club

>>> # Or
>>> [movie for movie in movie_list if keyword in movie]
['Pulp Fiction', 'Fight Club']
Reply
#5
>>> for movie in movie_list:
...     if keyword in movie:
THATS what I was missing thanks so much. Can finally move on
Reply
#6
Just also wondering how I would go about Adding the last displayed movie from a list to a new list. so for e.g

If the last movie shown on output was
pulp fiction

How would I add this to a list

Would it have something to do with .append ?

This kinda sums up what I am trying to do...

selection = input("Please Select:")
if selection =='sw':
   listb = movies_list
   letter = str(input("Search title starting with the letter: "))
   for movie in movies_list:
       if movie.startswith(letter):
           print(movie)
else:
   print("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='k':
   favlist = list.append(listb)
   print (favlist)
Reply
#7
listb is all the movies, and it's still a bad variable name. Giving your variables descriptive names will not only help us understand your code and thus help you, it will also help you see for yourself where the problems are in your code. Back to listb:

favlist = list.append(listb)
What you are doing is appending a list of all the movies to the list of all the movies, which isn't very useful. Also, the result of that is None. The append method changes the list in place, and doesn't return anything (this is a difference between list methods and string methods. So, an example with actual lists:

Output:
>>> users = ['ichabod801', 'snippsat', 'Mekire'] >>> coders = users >>> people = users.append(coders) >>> print(people) None >>> print(users) ['ichabod801', 'snippsat', 'Mekire', ['ichabod801', 'snippsat', 'Mekire']]
So, if you want to do something with the matching movies, you should save them in a list:

matches = []
letter = input('Search title starting with the letter: ') # input is already returning a str, you don't need to convert it.
for movie in movies_list:
    if movie.startswith(letter):
        matches.append(movie)
        print(movie)
Now you've got a list of movies matching the last criteria. If you have a list of favorite movies (call it favorites), you can use the extend method to add the items in the matches list to the favorites list.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
matches = []
letter = input('Search title starting with the letter: ') # input is already returning a str, you don't need to convert it.
for movie in movies_list:
   if movie.startswith(letter):
       matches.append(movie)
       print(movie)
Now you've got a list of movies matching the last criteria. If you have a list of favorite movies (call it favorites), you can use the extend method to add the items in the matches list to the favorites list.



Yup that is what I figured out I guess the only thing I am stuck on now is how do I make the selections for the menu repeat? What I mean is once a selection is made if its not in the order that the code has been written it just exits the program. I want to know how to be able to enter the commands multiple times and still go back to the main menu.

Sorry if that explanation is a little borked lol

Here is the whole code anyways

import random
import sys
from random import choice, sample
print("***Movie Title Explorer***")
def menu(): print("l – load file of movie titles"'\n'"r – random movie"'\n'"s– search"'\n'""
      "sw – starts with"'\n'"k – keep - save the last displayed movie title to your favourites"'\n'"f – favourites display"'\n'""
      "c – clear"'\n'"q - quit program")
menu()
print("command = ?")

selection=input("Please Select:")
l = file = open("C:\\Users\\LiquidO\\Desktop\\Assingment 2 python\\movies.txt", "r")
if selection =='l':
    movies_list = file.readlines()
    movies_list = [movie.strip() for movie in movies_list]
    print("Movies now loaded")
else:
    print ("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='r':
 print("Random choice selected")
 r = print(random.choice(movies_list))
else:
    print ("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='s':
    list = movies_list
    keyword = str(input("Search keyword: "))
    for movie in movies_list:
        if keyword in movie:
            print(movie)
else:
    print("Unknown Command")

menu()
favourite=[]
selection = input("Please Select:")
if selection =='sw':
    letter = str.upper(input("Search title starting with the letter: "))
    for movie in movies_list:
        if movie.startswith(letter):
            favourite.append(movie)
            print(movie)
else:
    print("Unknown Command")

menu()
selection = input("Please Select:")
if selection =='k':
   (favourite[-1])
   print("Last movie displayed saved to Favourites")
menu()
selection = input("Please Select:")
if selection =='f':
   print("Your Favourites List")
   print(favourite[-1])

menu()
selection = input("Please Select:")
if selection =='c':
    del favourite[:]
    print("Favourites List has been cleared")

menu()
selection = input("Please Select:")
if selection =='q':
    print("Bye!")
    sys.exit()
And the output 

***Movie Title Explorer***
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
command = ?
Please Select:l
Movies now loaded
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:r
Random choice selected
The Thin Red Line (1998)
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:s
Search keyword: de
Alexander Nevsky (1939)
All the President's Men (1976)
Amadeus (1984)
Anatomy of a Murder (1959)
Belle de Jour (1968)
Berlin Alexanderplatz (1983)
Bonnie and Clyde (1967)
The Bride Wore Black (1968)
Cavalcade (1933)
The Cider House Rules (1999)
The Citadel (1938)
Destry Rides Again (1939)
Dial M for Murder (1954)
Distant Thunder (1973)
Dr. Jekyll and Mr. Hyde (1932)
Double Indemnity (1944)
East of Eden (1955)
Fanny & Alexander (1983)
Father of the Bride (1950)
Forbidden Games (1952)
The Garden of the Finzi-Continis (1971)
Gentlemen Prefer Blondes (1953)
The Insider (1999)
It's a Wonderful Life (1946)
Jean de Florette (1987)
The King of Marvin Gardens (1972)
Kiss of the Spider Woman (1985)
L.A. Confidential (1997)
The Lavender Hill Mob (1951)
Loves of a Blonde (1966)
The Man With the Golden Arm (1955)
Memories of Underdevelopment (1973)
The Overlanders (1946)
The Ox-Bow Incident (1943)
Le Petit Theatre de Jean Renoir (1974)
The Philadelphia Story (1940)
Pride and Prejudice (1940)
The Pride of the Yankees (1942)
Raiders of the Lost Ark (1981)
Ride the High Country (1962)
Seven Brides for Seven Brothers (1954)
Sex, Lies and Videotape (1989)
A Slight Case of Murder (1938)
Suddenly, Last Summer (1959)
Tender Mercies (1983)
The Tender Trap (1955)
Terms of Endearment (1983)
Three Comrades (1938)
The Tree of the Wooden Clogs (1979)
Videodrome (1982)
West Side Story (1961)
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:sw
Search title starting with the letter: d
Damn Yankees (1958)
Dance with a Stranger (1985)
Dangerous Liaisons (1988)
Daniel (1983)
Danton (1983)
Dark Eyes (1987)
Dark Victory (1939)
Darling (1965)
David Copperfield (1935)
David Holtzman's Diary (1968, reviewed 1973)
Dawn of the Dead (1979)
Day for Night (1973)
Days of Heaven (1978)
Days of Wine and Roses (1963)
Dead Calm (1989)
Dead End (1937)
Dead Man Walking (1995)
Dead of Night (1946, reviewed 1946)
Dead Ringers (1988)
Death in Venice (1971)
Death of a Salesman (1951)
Deep End (1971)
Deliverance (1972)
Desperately Seeking Susan (1985)
Destry Rides Again (1939)
Diabolique (1955)
Dial M for Murder (1954)
Diary of a Chambermaid (1964)
Diary of a Country Priest (1950, reviewed 1954)
Die Hard (1988)
Diner (1982)
Dinner at Eight (1933)
Dirty Harry (1971)
Dirty Rotten Scoundrels (1988)
Disraeli (1929)
Distant Thunder (1973)
Diva (1982)
Divorce-Italian Style (1962)
Do the Right Thing (1989)
Dr. Jekyll and Mr. Hyde (1932)
Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb (1964)
Doctor Zhivago (1965)
Dodsworth (1936)
Donnie Brasco (1997)
Don't Look Back (1967)
Double Indemnity (1944)
Down by Law (1986)
Dracula (1931)
Dressed to Kill (1980)
Driving Miss Daisy (1989)
Drowning by Numbers (1991)
Drugstore Cowboy (1989)
Duck Soup (1933)
Dumbo (1941)
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:k
Last movie displayed saved to Favourites
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:f
Your Favourites List
Dumbo (1941)
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:c
Favourites List has been cleared
l – load file of movie titles
r – random movie
s– search
sw – starts with
k – keep - save the last displayed movie title to your favourites
f – favourites display
c – clear
q - quit program
Please Select:q
Bye!
Reply
#9
You need elif, which is an abbreviation for 'else if'. It gives another condition to check if the previous conditions haven't been met.

menu()
selection = input('What is your command? ').lower()
if command == 's':
    print('Spam spam spam spam')
elif command == 'c':
    print(1, 2, 5)
elif command == 'i':
    print('Nobody expects the Spanish Inquisition!')
else:
    print('Unknown command')
Typically, this sort of command checking is done in a while True: loop, with a break if the command is q, or quit, or exit, or something like that.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#10
(May-06-2017, 07:43 PM)ichabod801 Wrote: You need elif, which is an abbreviation for 'else if'. It gives another condition to check if the previous conditions haven't been met.

menu()
selection = input('What is your command? ').lower()
if command == 's':
    print('Spam spam spam spam')
elif command == 'c':
    print(1, 2, 5)
elif command == 'i':
    print('Nobody expects the Spanish Inquisition!')
else:
    print('Unknown command')
Typically, this sort of command checking is done in a while True: loop, with a break if the command is q, or quit, or exit, or something like that.


So for examples sake would I place that in here and then do it for each command?

selection=input("Please Select:")
l = file = open("C:\\Users\\LiquidO\\Desktop\\Assingment 2 python\\movies.txt", "r")
if selection =='l':
    movies_list = file.readlines()
    movies_list = [movie.strip() for movie in movies_list]
    print("Movies now loaded")
elif selection == 'r':
 print("Random choice selected")
r = print(random.choice(movies_list))
else:
    print ("Unknown Command")
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Collisions for items in a list Idents 3 2,282 Apr-06-2021, 03:48 PM
Last Post: deanhystad
  Removing items in a list cap510 3 2,331 Nov-01-2020, 09:53 PM
Last Post: cap510
  Help with Recursive solution,list items gianniskampanakis 8 3,570 Feb-28-2020, 03:36 PM
Last Post: gianniskampanakis
  Removing items from list slackerman73 8 4,405 Dec-13-2019, 05:39 PM
Last Post: Clunk_Head
  Find 'greater than' items in list johneven 2 4,456 Apr-05-2019, 07:22 AM
Last Post: perfringo
  How to add items within a list Mrocks22 2 2,663 Nov-01-2018, 08:46 PM
Last Post: Mrocks22
  printing list of random generated rectangles Zatoichi 8 7,333 Feb-18-2018, 06:34 PM
Last Post: buran
  How to keep duplicates and remove all other items in list? student8 1 4,937 Oct-28-2017, 05:52 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020