dictExample.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. #
  2. # dictExample.py
  3. #
  4. # Illustration of using pyparsing's Dict class to process tabular data
  5. #
  6. # Copyright (c) 2003, Paul McGuire
  7. #
  8. import pyparsing as pp
  9. testData = """
  10. +-------+------+------+------+------+------+------+------+------+
  11. | | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 |
  12. +=======+======+======+======+======+======+======+======+======+
  13. | min | 7 | 43 | 7 | 15 | 82 | 98 | 1 | 37 |
  14. | max | 11 | 52 | 10 | 17 | 85 | 112 | 4 | 39 |
  15. | ave | 9 | 47 | 8 | 16 | 84 | 106 | 3 | 38 |
  16. | sdev | 1 | 3 | 1 | 1 | 1 | 3 | 1 | 1 |
  17. +-------+------+------+------+------+------+------+------+------+
  18. """
  19. # define grammar for datatable
  20. heading = (pp.Literal(
  21. "+-------+------+------+------+------+------+------+------+------+") +
  22. "| | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 |" +
  23. "+=======+======+======+======+======+======+======+======+======+").suppress()
  24. vert = pp.Literal("|").suppress()
  25. number = pp.Word(pp.nums)
  26. rowData = pp.Group( vert + pp.Word(pp.alphas) + vert + pp.delimitedList(number,"|") + vert )
  27. trailing = pp.Literal(
  28. "+-------+------+------+------+------+------+------+------+------+").suppress()
  29. datatable = heading + pp.Dict(pp.ZeroOrMore(rowData)) + trailing
  30. # now parse data and print results
  31. data = datatable.parseString(testData)
  32. print(data)
  33. # shortcut for import pprint; pprint.pprint(data.asList())
  34. data.pprint()
  35. # access all data keys
  36. print("data keys=", list(data.keys()))
  37. # use dict-style access to values
  38. print("data['min']=", data['min'])
  39. # use attribute-style access to values (if key is a valid Python identifier)
  40. print("data.max", data.max)