[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1

Summing Columns in a File


Let’s look next at some practical applications of string splits and joins. In many do-
mains, scanning files by columns is a fairly common task. For instance, suppose you
have a file containing columns of numbers output by another system, and you need to
sum each column’s numbers. In Python, string splitting is the core operation behind
solving this problem, as demonstrated by Example 19-1. As an added bonus, it’s easy
to make the solution a reusable tool in Python by packaging it as an importable function.


Example 19-1. PP4E\Lang\summer.py


#!/usr/local/bin/python


def summer(numCols, fileName):
sums = [0] * numCols # make list of zeros
for line in open(fileName): # scan file's lines
cols = line.split() # split up columns
for i in range(numCols): # around blanks/tabs
sums[i] += eval(cols[i]) # add numbers to sums
return sums


if name == 'main':
import sys
print(summer(eval(sys.argv[1]), sys.argv[2])) # '% summer.py cols file'


Notice that we use file iterators here to read line by line, instead of calling the file
readlines method explicitly (recall from Chapter 4 that iterators avoid loading the
entire file into memory all at once). The file itself is a temporary object, which will be
automatically closed when garbage collected.


As usual for properly architected scripts, you can both import this module and call its
function, and run it as a shell tool from the command line. The summer.py script calls
split to make a list of strings representing the line’s columns, and eval to convert
column strings to numbers. Here’s an input file that uses both blanks and tabs to sep-
arate columns, and the result of turning our script loose on it:


C:\...\PP4E\Lang> type table1.txt
1 5 10 2 1.0
2 10 20 4 2.0
3 15 30 8 3
4 20 40 16 4.0

C:\...\PP4E\Lang> python summer.py 5 table1.txt
[10, 50, 100, 30, 10.0]

Also notice that because the summer script uses eval to convert file text to numbers,
you could really store arbitrary Python expressions in the file. Here, for example, it’s
run on a file of Python code snippets:


C:\...\PP4E\Lang> type table2.txt
2 1+1 1<<1 eval("2")
16 2*2*2*2 pow(2,4) 16.0

1410 | Chapter 19: Text and Language

Free download pdf