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

(yzsuai) #1
C:\...\PP4E\Lang> python
>>> print(open('table4.txt').read())
001.1 002.2 003.3
010.1 020.2 030.3 040.4
100.1 200.2 300.3

Here, we cannot preallocate a fixed-length list of sums because the number of columns
may vary. Splitting on whitespace extracts the columns, and float converts to numbers,
but a fixed-size list won’t easily accommodate a set of sums (at least, not without extra
code to manage its size). Dictionaries are more convenient here because we can use
column positions as keys instead of using absolute offsets. The following code dem-
onstrates interactively (it’s also in file summer3.py in the examples package):


>>> sums = {}
>>> for line in open('table4.txt'):
... cols = [float(col) for col in line.split()]
... for pos, val in enumerate(cols):
... sums[pos] = sums.get(pos, 0.0) + val
...
>>> for key in sorted(sums):
... print(key, '=', sums[key])
...
0 = 111.3
1 = 222.6
2 = 333.9
3 = 40.4

>>> sums
{0: 111.3, 1: 222.6, 2: 333.90000000000003, 3: 40.4}

Interestingly, most of this code uses tools added to Python over the years—file and
dictionary iterators, comprehensions, dict.get, and the enumerate and sorted built-ins
were not yet formed when Python was new. For related examples, also see the tkinter
grid examples in Chapter 9 for another case of eval table magic at work. That chapter’s
table sums logic is a variation on this theme, which obtains the number of columns
from the first line of a data file and tailors its summations for display in a GUI.


Parsing and Unparsing Rule Strings


Splitting comes in handy for dividing text into columns, but it can also be used as a
more general parsing tool—by splitting more than once on different delimiters, we can
pick apart more complex text. Although such parsing can also be achieved with more
powerful tools, such as the regular expressions we’ll meet later in this chapter, split-
based parsing is simper to code in quick prototypes, and may run faster.


For instance, Example 19-2 demonstrates one way that splitting and joining strings can
be used to parse sentences in a simple language. It is taken from a rule-based expert
system shell (holmes) that is written in Python and included in this book’s examples
distribution (more on holmes in a moment). Rule strings in holmes take the form:


"rule <id> if <test1>, <test2>... then <conclusion1>, <conclusion2>..."

1412 | Chapter 19: Text and Language

Free download pdf