parseTabularData.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #
  2. # parseTabularData.py
  3. #
  4. # Example of parsing data that is formatted in a tabular listing, with
  5. # potential for missing values. Uses new addCondition method on
  6. # ParserElements.
  7. #
  8. # Copyright 2015, Paul McGuire
  9. #
  10. from pyparsing import col,Word,Optional,alphas,nums
  11. table = """\
  12. 1 2
  13. 12345678901234567890
  14. COLOR S M L
  15. RED 10 2 2
  16. BLUE 5 10
  17. GREEN 3 5
  18. PURPLE 8"""
  19. # function to create column-specific parse conditions
  20. def mustMatchCols(startloc,endloc):
  21. return lambda s,l,t: startloc <= col(l,s) <= endloc
  22. # helper to define values in a space-delimited table
  23. # (change empty_cell_is_zero to True if a value of 0 is desired for empty cells)
  24. def tableValue(expr, colstart, colend):
  25. empty_cell_is_zero = False
  26. if empty_cell_is_zero:
  27. return Optional(expr.copy().addCondition(mustMatchCols(colstart,colend),
  28. message="text not in expected columns"),
  29. default=0)
  30. else:
  31. return Optional(expr.copy().addCondition(mustMatchCols(colstart,colend),
  32. message="text not in expected columns"))
  33. # define the grammar for this simple table
  34. colorname = Word(alphas)
  35. integer = Word(nums).setParseAction(lambda t: int(t[0])).setName("integer")
  36. row = (colorname("name") +
  37. tableValue(integer, 11, 12)("S") +
  38. tableValue(integer, 15, 16)("M") +
  39. tableValue(integer, 19, 20)("L"))
  40. # parse the sample text - skip over the header and counter lines
  41. for line in table.splitlines()[3:]:
  42. print(line)
  43. print(row.parseString(line).dump())
  44. print('')