Prof. Andrea Gallegati
This case study involves solving word puzzles by searching for words that have certain properties.
... one most suitable one, is by Grady Ward (Moby lexicon project): 113,809
official crosswords:
http://wikipedia.org/wiki/Moby_Project
considered valid in crossword puzzles and other word games.
This plain text file (words.txt
), can be opened with a text editor or read from Python
fin = open('doc/words.txt')
this built-in function takes the name of the file as a parameter and returns a file object to read.
These two are, of course, distinct entities
fin
is a common name for a file object, used for input.
The file object provides several methods for reading.
readline
, reads characters until a newline is reached and returns them as a string
fin.readline()
'aa\n'
This first word is a kind of lava.
The sequence \r\n
, that separate this word from the next, represents:
The file object keeps track of where it is in the file:
recalling readline
, we get the next word.
fin.readline()
'aah\n'
which is a perfectly legitimate word.
Want to get rid of whitespaces?
Just use the string method strip
:
line = fin.readline()
word = line.strip()
word
'aahed'
We can even loop over a file object.
fin = open('words.txt')
for line in fin:
word = line.strip()
print(word)
This program reads each word within words.txt
, line by line
Attempt each one before reading the solutions, in the following slides!