# go through a text file, looking for hidden Beatles lyrics # and it will work with any bit of lyrics we ask it to search for # example: searchLyrics("TopSecretMilitaryInfo.txt","I am the Walrus") class TheBeatDoesntGoOnException (Exception) : pass # notice the lack of print(), I would never make a mistake and need to put # in print() to debug it def searchLyrics(src,lyric) : '''Given a file path and a string with some lyrics, go through the file looking for the emedded lyrics (in order), and return True or raise a TheSongDoesntGoOnException.''' s = open(src,"r") # split the words up, assuming that lyric has words separated by spaces words = lyric.split(" ") line = s.readline() # str.find() returns -1 when it doesn't find something, which is # "before" the first character in the string. We use this as the # position of the last-found word lastFoundIndex = -1 for word in words: while line.find(word) <= lastFoundIndex : # when the word is not found, we go to the next line, # resetting the location of the last find to the beginning of the line line = s.readline() lastFoundIndex = -1 # if the line is empty, we got to the end of the file without # finding all the words, so we raise an exception if line == "" : raise TheBeatDoesntGoOnException # we only exit the while loop after finding a word, so we need to # reset the lastFoundIndex, and we DO NOT read another line, # first searching for the next word LATER in the current line lastFoundIndex = line.find(word) # if we get through all of the words, then we have found the lyrics! return True