dictExample2.py :  » Parser » pyparsing » pyparsing-1.5.2 » examples » Python Open Source

Home
Python Open Source
1.3.1.2 Python
2.Ajax
3.Aspect Oriented
4.Blog
5.Build
6.Business Application
7.Chart Report
8.Content Management Systems
9.Cryptographic
10.Database
11.Development
12.Editor
13.Email
14.ERP
15.Game 2D 3D
16.GIS
17.GUI
18.IDE
19.Installer
20.IRC
21.Issue Tracker
22.Language Interface
23.Log
24.Math
25.Media Sound Audio
26.Mobile
27.Network
28.Parser
29.PDF
30.Project Management
31.RSS
32.Search
33.Security
34.Template Engines
35.Test
36.UML
37.USB Serial
38.Web Frameworks
39.Web Server
40.Web Services
41.Web Unit
42.Wiki
43.Windows
44.XML
Python Open Source » Parser » pyparsing 
pyparsing » pyparsing 1.5.2 » examples » dictExample2.py
#
# dictExample2.py
#
#  Illustration of using pyparsing's Dict class to process tabular data
#  Enhanced Dict example, courtesy of Mike Kelly
#
# Copyright (c) 2004, Paul McGuire
#
from pyparsing import Literal,Word,Group,Dict,ZeroOrMore,alphas,nums,delimitedList
import pprint

testData = """
+-------+------+------+------+------+------+------+------+------+
|       |  A1  |  B1  |  C1  |  D1  |  A2  |  B2  |  C2  |  D2  |
+=======+======+======+======+======+======+======+======+======+
| min   |   7  |  43  |   7  |  15  |  82  |  98  |   1  |  37  |
| max   |  11  |  52  |  10  |  17  |  85  | 112  |   4  |  39  |
| ave   |   9  |  47  |   8  |  16  |  84  | 106  |   3  |  38  |
| sdev  |   1  |   3  |   1  |   1  |   1  |   3  |   1  |   1  |
+-------+------+------+------+------+------+------+------+------+
"""

# define grammar for datatable
underline = Word("-=")
number = Word(nums).setParseAction( lambda t : int(t[0]) )
vert = Literal("|").suppress()

rowDelim = ("+" + ZeroOrMore( underline + "+" ) ).suppress()
columnHeader = Group(vert + vert + delimitedList(Word(alphas + nums), "|") + vert)

heading = rowDelim + columnHeader.setResultsName("columns") + rowDelim
rowData = Group( vert + Word(alphas) + vert + delimitedList(number,"|") + vert )
trailing = rowDelim

datatable = heading + Dict( ZeroOrMore(rowData) ) + trailing

# now parse data and print results
data = datatable.parseString(testData)
print data
print data.asXML("DATA")
pprint.pprint(data.asList())
print "data keys=", data.keys()
print "data['min']=", data['min']
print "sum(data['min']) =", sum(data['min'])
print "data.max =", data.max
print "sum(data.max) =", sum(data.max)

# now print transpose of data table, using column labels read from table header and 
# values from data lists
print 
print " " * 5,
for i in range(1,len(data)):
    print "|%5s" % data[i][0],
print
print ("-" * 6) + ("+------" * (len(data)-1))
for i in range(len(data.columns)):
    print "%5s" % data.columns[i],
    for j in range(len(data) - 1):
        print '|%5s' % data[j + 1][i + 1],
    print 
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.