Operation Manual
Experiments in Python
93
Notes:
Film search
# sort a le full of lm names
# function to compare the lowercase item with the searchfor
def compare(item):
return searchfor in it e m.low e r()
# load the le into a list and
# close the le because the content is now in memory
with open("lmlist", "r") as lm:
lmlist = lm.read().splitlines()
searchfor = input("Enter part of the lm \
name you are searching for: "). l o w e r(). s t r i p( )
# use the built-in lter function, which will
# call the rst parameter on every item on
# the list and, if it is true, it will use the item
foundlist = lter(compare, lmlist)
for name in foundlist:
print(na me)
As in the previous experiment, the plan is to load a list of film names and then
process them. In this case, the requirement is to find a film requested by the user.
The film list we created previously is loaded into memory. Text to “searchfor” is
requested from the user. This is immediately converted to lowercase characters
and any extra spaces stripped. During the search, any film title will also be
converted to lowercase before checking so that case will not be relevant to
the search.
There is a Python function called “filter”, which will take a list and generate a new
list by filtering out any entries that do not pass a test. In this case, our test will
compare the user’s query text with the entry being tested.
Lastly, the entries in the list of found items are printed to the screen.
Long lines
The input line has a “\” character half way through the question.
This was added because the line was long. If the input question
was typed on just one line, it would not need this character. A “\”
character at the end of a line is a continuation marker. It indicates
that the line hasn’t finished yet and it will continue on the next
line of the program. When the program is run, this character won’t
appear in the result – it is only used by the program interpreter to
keep track of the flow of the code.