Solutions for Part B: Strings, ..., File I/O exercises
1. Accessing and Storing Web Files
# GetGA.py
#
import urllib
FileURL = 'http://csc.ucdavis.edu/~chaos/courses/clab/Homework/GettysburgAddress.txt'
file = open('ga.txt','w')
for line in urllib.urlopen(FileURL):
file.write(line)
file.close()
2. Counting lines and words in a file
# WordLineCounts.py
#
lines = 0
words = 0
f = open('ga.txt')
for line in f:
lines = lines + 1
words = words + len(line.split())
f.close()
print lines, " lines, ", words, " words."
This program can be tested by running the Unix utility wc for
comparison.
3. Counting vowels in a file
# VowelCounts.py
#
nLines = 0
nAs = 0
nEs = 0
nIs = 0
nOs = 0
nUs = 0
f = open('ga.txt')
for line in f:
nLines = nLines + 1
for letter in line:
if letter == 'a':
nAs = nAs + 1
elif letter == 'e':
nEs = nEs + 1
elif letter == 'i':
nIs = nIs + 1
elif letter == 'o':
nOs = nOs + 1
elif letter == 'u':
nUs = nUs + 1
print "File has:"
print nAs, " As"
print nEs, " Es"
print nIs, " Is"
print nOs, " Os"
print nUs, " Us"
4. Sort lines in a file
# SortFile.py
#
InputFileName = 'ga.txt'
Lines = []
f = open(InputFileName)
for line in f:
Lines.append(line)
f.close()
Lines.sort()
SortedFileName = 'ga_sorted.txt'
file = open(SortedFileName, 'w')
for line in Lines:
file.write(line)
file.close()
5. Iterate a one-dimensional map, storing results in a file
# OneDMapIterate.py
#
OutputFileName = "onedmap.txt"
nIterations = 20
x = 0.3
r = 4.0
file = open(OutputFileName, 'w')
for i in range(nIterations):
x = r * x * (1.0 - x)
line = str(i) + ' ' + str(x) + '\n'
file.write(line)
file.close()
Here what the file contains:
In [35]: cat onedmap.txt
0 0.84
1 0.5376
2 0.99434496
3 0.0224922420904
4 0.0879453645446
5 0.320843909599
6 0.871612381089
7 0.447616952887
8 0.989024065501
9 0.0434218534453
10 0.166145584355
11 0.554164916617
12 0.988264647232
13 0.0463905370552
14 0.176953820508
15 0.582564663661
16 0.972732305258
17 0.106096670262
18 0.379360667285
19 0.941784605609
6. Analyze a chaotic one-dimensional map
# OneDMapAnalyze.py
#
MeanValue = 0.0
nIterates = 0
f = open('onedmap.txt')
for line in f:
n, x = line.split()
MeanValue = MeanValue + float(x)
nIterates = nIterates + 1
f.close()
print "Average value = ",MeanValue/float(nIterates)
Table of Contents