Lesson 13 - Case study: Word play

Download Report

Transcript Lesson 13 - Case study: Word play

Day 4 – Lesson 13
Case study: Word play
Python Mini-Course
University of Oklahoma
Department of Psychology
1
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Lesson objectives
1. Read in values from a text file
2. Create useful functions for
identifying patterns in text
2
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Files in Python
 Files are objects
 http://www.python.org/doc/2.5.2/lib
/bltin-file-objects.html
 Use the open statement to
instantiate a file object
fin = open('words.txt', 'r')
print fin
3
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Files in Python
 File methods include
f.readline()
f.write()
f.close()
4
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Reading a line
fin = open('words.txt', 'r')
line = fin.readline()
print line
line = fin.readline()
print word
5
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Reading a line
word = line.strip()
print word
word = fin.readline().strip()
print word
fin.close()
6
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Iterating through the lines
fin = open('words.txt')
for line in fin:
word = line.strip()
print word
fin.close()
7
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Exercise 9.1
 Write a program that reads
words.txt and prints only the
words with more than 20
characters (not counting
whitespace)
8
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Exercise 9.2
1. Write a function called has_no_e
that returns True if the given word
doesn’t have the letter “e” in it.
2. Modify your program from the
previous section to print only the
words that have no “e” and compute
the percentage of the words in the
list have no “e.”
9
Python Mini-Course: Day 4 – Lesson 13
05/02/09
Suggested exercises
 Any (or all) of the remaining
Exercises from Chapters 8 and 9 of
Think Python
10
Python Mini-Course: Day 4 – Lesson 13
05/02/09