12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 9Case study: word play9.1 Readingword listsFor the exercises in this chapter we need a list of English words. There are lots of word listsavailableontheWeb,buttheonemostsuitableforourpurposeisoneofthewordlistscollectedandcontributed to the public domain by Grady Ward as part of the Moby lexicon project 1 . It is a list of113,809 official crosswords; that is, words that are considered valid in crossword puzzles and otherword games. In the Moby collection, the filename is 113809of.fic; I include a copy of this file,withthesimpler namewords.txt,along withSwampy.This file is in plain text, so you can open it with a text editor, but you can also read it from <strong>Python</strong>.Thebuilt-infunctionopentakesthenameofthefileasaparameterandreturnsafileobjectyoucanusetoread thefile.>>> fin = open('words.txt')>>> print finfin is a common name for a file object used for input. Mode'r' indicates that this file is open forreading (as opposed to'w' forwriting).The file object provides several methods for reading, including readline, which reads charactersfrom thefileuntil it gets toanewline and returnsthe resultas astring:>>> fin.readline()'aa\r\n'The first word in this particular list is “aa,” which is a kind of lava. The sequence \r\n representstwowhitespace characters, acarriage returnand anewline, that separate this wordfrom thenext.The file object keeps track of where it is in the file, so if you call readline again, you get the nextword:>>> fin.readline()'aah\r\n'1 wikipedia.org/wiki/Moby_Project.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!