CIS 1051 - Temple Rome Spring 2023¶

Intro to Problem solving and¶

Programming in Python¶

LOGO

LOGO

Word Play¶

Prof. Andrea Gallegati

( tuj81353@temple.edu )

This case study involves solving word puzzles by searching for words that have certain properties.

Reading Word Lists¶

... 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

In [5]:
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

  • a String object
  • a File object

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

In [6]:
fin.readline()
Out[6]:
'aa\n'

This first word is a kind of lava.

The sequence \r\n, that separate this word from the next, represents:

  • two whitespace characters
  • a carriage return
  • a newline.

The file object keeps track of where it is in the file:

recalling readline, we get the next word.

In [7]:
fin.readline()
Out[7]:
'aah\n'

which is a perfectly legitimate word.

Want to get rid of whitespaces?

Just use the string method strip:

In [8]:
line = fin.readline()
word = line.strip()
word
Out[8]:
'aahed'

We can even loop over a file object.

In [ ]:
fin = open('words.txt')
for line in fin:
    word = line.strip()
    print(word)

This program reads each word within words.txt, line by line

Case Study¶

Attempt each one before reading the solutions, in the following slides!