dictExample2.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. #
  2. # dictExample2.py
  3. #
  4. # Illustration of using pyparsing's Dict class to process tabular data
  5. # Enhanced Dict example, courtesy of Mike Kelly
  6. #
  7. # Copyright (c) 2004, Paul McGuire
  8. #
  9. from pyparsing import Literal, Word, Group, Dict, ZeroOrMore, alphas, nums, delimitedList, pyparsing_common as ppc
  10. testData = """
  11. +-------+------+------+------+------+------+------+------+------+
  12. | | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 |
  13. +=======+======+======+======+======+======+======+======+======+
  14. | min | 7 | 43 | 7 | 15 | 82 | 98 | 1 | 37 |
  15. | max | 11 | 52 | 10 | 17 | 85 | 112 | 4 | 39 |
  16. | ave | 9 | 47 | 8 | 16 | 84 | 106 | 3 | 38 |
  17. | sdev | 1 | 3 | 1 | 1 | 1 | 3 | 1 | 1 |
  18. +-------+------+------+------+------+------+------+------+------+
  19. """
  20. # define grammar for datatable
  21. underline = Word("-=")
  22. number = ppc.integer
  23. vert = Literal("|").suppress()
  24. rowDelim = ("+" + ZeroOrMore( underline + "+" ) ).suppress()
  25. columnHeader = Group(vert + vert + delimitedList(Word(alphas + nums), "|") + vert)
  26. heading = rowDelim + columnHeader("columns") + rowDelim
  27. rowData = Group( vert + Word(alphas) + vert + delimitedList(number,"|") + vert )
  28. trailing = rowDelim
  29. datatable = heading + Dict( ZeroOrMore(rowData) ) + trailing
  30. # now parse data and print results
  31. data = datatable.parseString(testData)
  32. print(data.dump())
  33. print("data keys=", list(data.keys()))
  34. print("data['min']=", data['min'])
  35. print("sum(data['min']) =", sum(data['min']))
  36. print("data.max =", data.max)
  37. print("sum(data.max) =", sum(data.max))
  38. # now print transpose of data table, using column labels read from table header and
  39. # values from data lists
  40. print()
  41. print(" " * 5, end=' ')
  42. for i in range(1,len(data)):
  43. print("|%5s" % data[i][0], end=' ')
  44. print()
  45. print(("-" * 6) + ("+------" * (len(data)-1)))
  46. for i in range(len(data.columns)):
  47. print("%5s" % data.columns[i], end=' ')
  48. for j in range(len(data) - 1):
  49. print('|%5s' % data[j + 1][i + 1], end=' ')
  50. print()