Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 13 Case study: Word play 05/02/09 Python Mini-Course: Day 4 – Lesson.

Similar presentations


Presentation on theme: "Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 13 Case study: Word play 05/02/09 Python Mini-Course: Day 4 – Lesson."— Presentation transcript:

1 Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 13 Case study: Word play 05/02/09 Python Mini-Course: Day 4 – Lesson 13 1

2 Lesson objectives 1. Read in values from a text file 2. Create useful functions for identifying patterns in text 05/02/09 Python Mini-Course: Day 4 – Lesson 13 2

3 Files in Python Files are objects http://www.python.org/doc/2.5.2/lib /bltin-file-objects.html 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 05/02/09 Python Mini-Course: Day 4 – Lesson 13 3

4 Files in Python File methods include f.readline() f.write() f.close() 05/02/09 Python Mini-Course: Day 4 – Lesson 13 4

5 Reading a line fin = open('words.txt', 'r') line = fin.readline() print line line = fin.readline() print word 05/02/09 Python Mini-Course: Day 4 – Lesson 13 5

6 Reading a line word = line.strip() print word word = fin.readline().strip() print word fin.close() 05/02/09 Python Mini-Course: Day 4 – Lesson 13 6

7 Iterating through the lines fin = open('words.txt') for line in fin: word = line.strip() print word fin.close() 05/02/09 Python Mini-Course: Day 4 – Lesson 13 7

8 Exercise 9.1 Write a program that reads words.txt and prints only the words with more than 20 characters (not counting whitespace) 05/02/09 Python Mini-Course: Day 4 – Lesson 13 8

9 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.” 05/02/09 Python Mini-Course: Day 4 – Lesson 13 9

10 Suggested exercises Any (or all) of the remaining Exercises from Chapters 8 and 9 of Think Python 05/02/09 Python Mini-Course: Day 4 – Lesson 13 10


Download ppt "Python Mini-Course University of Oklahoma Department of Psychology Day 4 – Lesson 13 Case study: Word play 05/02/09 Python Mini-Course: Day 4 – Lesson."

Similar presentations


Ads by Google