Skip to content

Commit c8fdea3

Browse files
committed
Add the remaining VerbatimInput lines.
1 parent 2b41fb4 commit c8fdea3

20 files changed

+36032
-867
lines changed

book/07-files.mkd

Lines changed: 26 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -22,10 +22,10 @@ power is turned off, anything stored in either the CPU or main memory is
2222
erased. So up to now, our programs have just been transient fun
2323
exercises to learn Python.
2424

25-
![Secondary Memory](height=1.0in@../images/arch)
25+
![Secondary Memory](height=2.5in@../images/arch)
2626

2727
In this chapter, we start to work with *Secondary Memory*
28-
(or files). Secondary memory is not erased even when the power is turned
28+
(or files). Secondary memory is not erased when the power is turned
2929
off. Or in the case of a USB flash drive, the data we write from our
3030
programs can be removed from the system and transported to another
3131
system.
@@ -222,10 +222,10 @@ started with the prefix "From:", we could use the string method
222222
*startswith* to select only those lines with the desired
223223
prefix:
224224

225-
fhand = open('mbox-short.txt')
226-
for line in fhand:
227-
if line.startswith('From:'):
228-
print(line)
225+
\VerbatimInput{../code3/search1.py}
226+
\begin{trinketfiles}
227+
../code3/mbox-short.txt
228+
\end{trinketfiles}
229229

230230
When this program runs, we get the following output:
231231

@@ -250,11 +250,10 @@ We could use line slicing to print all but the last character, but a
250250
simpler approach is to use the *rstrip* method which
251251
strips whitespace from the right side of a string as follows:
252252

253-
fhand = open('mbox-short.txt')
254-
for line in fhand:
255-
if line.startswith('From:'):
256-
line = line.rstrip()
257-
print(line)
253+
\VerbatimInput{../code3/search2.py}
254+
\begin{trinketfiles}
255+
../code3/mbox-short.txt
256+
\end{trinketfiles}
258257

259258
When this program runs, we get the following output:
260259

@@ -276,14 +275,10 @@ interesting line, we do something with that line.
276275
We can structure the loop to follow the pattern of skipping
277276
uninteresting lines as follows:
278277

279-
fhand = open('mbox-short.txt')
280-
for line in fhand:
281-
# Skip 'uninteresting lines'
282-
if not line.startswith('From:'):
283-
continue
284-
# Process our 'interesting' line
285-
line = line.rstrip()
286-
print(line)
278+
\VerbatimInput{../code3/search3.py}
279+
\begin{trinketfiles}
280+
../code3/mbox-short.txt
281+
\end{trinketfiles}
287282

288283
The output of the program is the same. In English, the uninteresting
289284
lines are those which do not start with "From:", which we skip using
@@ -298,12 +293,10 @@ the string was not found, we can write the following loop to show lines
298293
which contain the string "@uct.ac.za" (i.e., they come from the
299294
University of Cape Town in South Africa):
300295

301-
fhand = open('mbox-short.txt')
302-
for line in fhand:
303-
line = line.rstrip()
304-
if line.find('@uct.ac.za') == -1:
305-
continue
306-
print(line)
296+
\VerbatimInput{../code3/search4.py}
297+
\begin{trinketfiles}
298+
../code3/mbox-short.txt
299+
\end{trinketfiles}
307300

308301
Which produces the following output:
309302

@@ -328,13 +321,10 @@ our program on different files without changing the Python code.
328321
This is quite simple to do by reading the file name from the user using
329322
`raw_input` as follows:
330323

331-
fname = input('Enter the file name: ')
332-
fhand = open(fname)
333-
count = 0
334-
for line in fhand:
335-
if line.startswith('Subject:'):
336-
count = count + 1
337-
print('There were', count, 'subject lines in', fname)
324+
\VerbatimInput{../code3/search6.py}
325+
\begin{trinketfiles}
326+
../code3/mbox-short.txt
327+
\end{trinketfiles}
338328

339329
We read the file name from the user and place it in a variable named
340330
`fname` and open that file. Now we can run the program
@@ -402,18 +392,10 @@ using the `try`/`except` structure. We need to
402392
assume that the `open` call might fail and add recovery code
403393
when the `open` fails as follows:
404394

405-
fname = input('Enter the file name: ')
406-
try:
407-
fhand = open(fname)
408-
except:
409-
print('File cannot be opened:', fname)
410-
exit()
411-
412-
count = 0
413-
for line in fhand:
414-
if line.startswith('Subject:'):
415-
count = count + 1
416-
print('There were', count, 'subject lines in', fname)
395+
\VerbatimInput{../code3/search7.py}
396+
\begin{trinketfiles}
397+
../code3/mbox-short.txt
398+
\end{trinketfiles}
417399

418400
The `exit` function terminates the program. It is a function
419401
that we call that never returns. Now when our user (or QA team) types in

book/08-lists.mkd

Lines changed: 6 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -383,17 +383,7 @@ of numbers entered by the user using a list.
383383

384384
First, the program to compute an average without a list:
385385

386-
total = 0
387-
count = 0
388-
while ( True ) :
389-
inp = input('Enter a number: ')
390-
if inp == 'done' : break
391-
value = float(inp)
392-
total = total + value
393-
count = count + 1
394-
395-
average = total / count
396-
print('Average:', average)
386+
\VerbatimInput{../code3/avenum.py}
397387

398388
In this program, we have `count` and `total`
399389
variables to keep the number and running total of the user's numbers as
@@ -402,15 +392,7 @@ we repeatedly prompt the user for a number.
402392
We could simply remember each number as the user entered it and use
403393
built-in functions to compute the sum and count at the end.
404394

405-
numlist = list()
406-
while ( True ) :
407-
inp = input('Enter a number: ')
408-
if inp == 'done' : break
409-
value = float(inp)
410-
numlist.append(value)
411-
412-
average = sum(numlist) / len(numlist)
413-
print('Average:', average)
395+
\VerbatimInput{../code3/avelist.py}
414396

415397
We make an empty list before the loop starts, and then each time we have
416398
a number, we append it to the list. At the end of the program, we simply
@@ -509,12 +491,10 @@ kind of problem. We can write a small program that looks for lines where
509491
the line starts with "From ", `split` those lines, and then
510492
print out the third word in the line:
511493

512-
fhand = open('mbox-short.txt')
513-
for line in fhand:
514-
line = line.rstrip()
515-
if not line.startswith('From ') : continue
516-
words = line.split()
517-
print(words[2])
494+
\VerbatimInput{../code3/search5.py}
495+
\begin{trinketfiles}
496+
../code3/mbox-short.txt
497+
\end{trinketfiles}
518498

519499
Here we also use the contracted form of the `if` statement
520500
where we put the `continue ` on the same line as the

book/09-dictionaries.mkd

Lines changed: 8 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -274,23 +274,10 @@ iterating "more quickly" and the outer loop as iterating more slowly.
274274
The combination of the two nested loops ensures that we will count every
275275
word on every line of the input file.
276276

277-
fname = input('Enter the file name: ')
278-
try:
279-
fhand = open(fname)
280-
except:
281-
print('File cannot be opened:', fname)
282-
exit()
283-
284-
counts = dict()
285-
for line in fhand:
286-
words = line.split()
287-
for word in words:
288-
if word not in counts:
289-
counts[word] = 1
290-
else:
291-
counts[word] += 1
292-
293-
print(counts)
277+
\VerbatimInput{../code3/count1.py}
278+
\begin{trinketfiles}
279+
../code3/romeo.txt
280+
\end{trinketfiles}
294281

295282
When we run the program, we see a raw dump of all of the counts in
296283
unsorted hash order. (the `romeo.txt` file is available at
@@ -427,27 +414,10 @@ will even let Python tell us the list of characters that it considers
427414

428415
We make the following modifications to our program:
429416

430-
import string # New Code
431-
432-
fname = input('Enter the file name: ')
433-
try:
434-
fhand = open(fname)
435-
except:
436-
print('File cannot be opened:', fname)
437-
exit()
438-
439-
counts = dict()
440-
for line in fhand:
441-
line = line.translate(None, string.punctuation) # New Code
442-
line = line.lower() # New Code
443-
words = line.split()
444-
for word in words:
445-
if word not in counts:
446-
counts[word] = 1
447-
else:
448-
counts[word] += 1
449-
450-
print(counts)
417+
\VerbatimInput{../code3/count2.py}
418+
\begin{trinketfiles}
419+
../code3/romeo-full.txt
420+
\end{trinketfiles}
451421

452422
We use `translate` to remove all punctuation and
453423
`lower` to force the line to lowercase. Otherwise the program

book/10-tuples.mkd

Lines changed: 5 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -155,19 +155,7 @@ Undecorate
155155
For example, suppose you have a list of words and you want to sort them
156156
from longest to shortest:
157157

158-
txt = 'but soft what light in yonder window breaks'
159-
words = txt.split()
160-
t = list()
161-
for word in words:
162-
t.append((len(word), word))
163-
164-
t.sort(reverse=True)
165-
166-
res = list()
167-
for length, word in t:
168-
res.append(word)
169-
170-
print(res)
158+
\VerbatimInput{../code3/soft.py}
171159

172160
The first loop builds a list of tuples, where each tuple is a word
173161
preceded by its length.
@@ -383,28 +371,10 @@ Coming back to our running example of the text from *Romeo and Juliet*
383371
Act 2, Scene 2, we can augment our program to use this technique to
384372
print the ten most common words in the text as follows:
385373

386-
import string
387-
fhand = open('romeo-full.txt')
388-
counts = dict()
389-
for line in fhand:
390-
line = line.translate(None, string.punctuation)
391-
line = line.lower()
392-
words = line.split()
393-
for word in words:
394-
if word not in counts:
395-
counts[word] = 1
396-
else:
397-
counts[word] += 1
398-
399-
# Sort the dictionary by value
400-
lst = list()
401-
for key, val in list(counts.items()):
402-
lst.append( (val, key) )
403-
404-
lst.sort(reverse=True)
405-
406-
for key, val in lst[:10] :
407-
print(key, val)
374+
\VerbatimInput{../code3/count3.py}
375+
\begin{trinketfiles}
376+
../code3/romeo-full.txt
377+
\end{trinketfiles}
408378

409379
The first part of the program which reads the file and computes the
410380
dictionary that maps each word to the count of words in the document is

0 commit comments

Comments
 (0)