Functional Python Programming

(Wang) #1
Chapter 4

The result of this function is an iterable sequence of rows of data. Each row will be a
tuple composed of three strings: latitude, longitude, and altitude of a waypoint
along this path. This isn't directly useful yet. We'll need to do some more processing
to get latitude and longitude as well as converting these two numbers into useful
floating-point values.


This idea of an iterable sequence of tuples as results of lower-level parsing allows
us to process some kinds of data files in a simple and uniform way. In Chapter 3,
Functions, Iterators, and Generators, we looked at how Comma Separated Values
(CSV) files are easily handled as rows of tuples. In Chapter 6, Recursions and
Reductions, we'll revisit the parsing idea to compare these various examples.


The output from the preceding function looks like the following code snippet:


[['-76.33029518659048', '37.54901619777347', '0'],
['-76.27383399999999', '37.840832', '0'],
['-76.459503', '38.331501', '0'],
and so on
['-76.47350299999999', '38.976334', '0']]


Each row is the source text of the tag split using , that's part
of the text content. The values are the East-West longitude, North-South latitude,
and altitude. We'll apply some additional functions to the output of this function
to create a usable set of data.


Parsing a file at a higher level


Once we've parsed the low-level syntax, we can restructure the raw data into
something usable in our Python program. This kind of structuring applies to XML,
JavaScript Object Notation (JSON), CSV, and any of the wide variety of physical
formats in which data is serialized.


We'll aim to write a small suite of generator functions that transforms the parsed
data into a form our application can use. The generator functions include some
simple transformations on the text that's found by the row_iter_kml() function,
which are as follows:



  • Discarding altitude, or perhaps keeping only latitude and longitude

  • Changing the order from (longitude, latitude) to (latitude, longitude)


We can make these two transformations have more syntactic uniformity by defining
a utility function as follows:


def pick_lat_lon(lon, lat, alt):
return lat, lon

Free download pdf