|
First Summer 2006 |
Today's lab will be about the material in Chapter 7 in the Python text.
The lab material and the lab assignment will be posted here shortly.
This is your lab assignment for today, Tuesday May 23, 2006:Write a program that
- opens a text file for reading
- reads the entire contents, and reports
(a) the longest line in the file (in number of characters)
(b) the longest line in the file (in number of non-blank characters) and
(c) the line that has the largest number of words on itTurn in your programs in OnCourse (under A201-7055) by the end of the day.
To help with this assignment let's review a number of features.
Here's how you split a line into tokens:
Python 2.2.3 (#42, May 30 2003, 18:12:08) [MSC 32 bit (Intel)] on win32 Type "copyright", "credits" or "license" for more information. IDLE 0.8 -- press F1 for help >>> line = "This is a line and it has several tokens on it." >>> line 'This is a line and it has several tokens on it.' >>> line.split() ['This', 'is', 'a', 'line', 'and', 'it', 'has', 'several', 'tokens', 'on', 'it.'] >>> >>> for token in line.split(): print token This is a line and it has several tokens on it. >>>
Now let's assume we have a file, called data.txt on the desktop.
This is how we can get the lines out of the file:
# looping through the file line by line
file = open("C:/Documents and Settings/dgerman/Desktop/data.txt", "r")
for line in file:
print line
file.close()
raw_input("Press enter to quit...")You need to be careful with the file extension and with the path to the file.
My file's contents is:
I've watched the stars fall silent from your eyes All the sights that I have seen I can't believe that I believed I wished That you could see There's a new planet in the solar system There is nothing up my sleeve I'm pushing an elephant up the stairs I'm tossing up punch lines that were never there Over my shoulder a piano falls Crashing to the ground
You will notice that when you print the lines you get extra new lines.
Now here's a program that finds the largest element in a list of numbers:
a = [ 3, 1, 6, 3, 4, 2, 9, 5, 4, 8]
max = a[0]
for elem in a:
if elem > max:
max = elem
print maxWith this you should have all you need to finish your lab assignment.