linenoExample.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #
  2. # linenoExample.py
  3. #
  4. # an example of using the location value returned by pyparsing to
  5. # extract the line and column number of the location of the matched text,
  6. # or to extract the entire line of text.
  7. #
  8. # Copyright (c) 2006, Paul McGuire
  9. #
  10. from pyparsing import *
  11. data = """Now is the time
  12. for all good men
  13. to come to the aid
  14. of their country."""
  15. # demonstrate use of lineno, line, and col in a parse action
  16. def reportLongWords(st,locn,toks):
  17. word = toks[0]
  18. if len(word) > 3:
  19. print("Found '%s' on line %d at column %d" % (word, lineno(locn,st), col(locn,st)))
  20. print("The full line of text was:")
  21. print("'%s'" % line(locn,st))
  22. print((" "*col(locn,st))+" ^")
  23. print()
  24. wd = Word(alphas).setParseAction( reportLongWords )
  25. OneOrMore(wd).parseString(data)
  26. # demonstrate returning an object from a parse action, containing more information
  27. # than just the matching token text
  28. class Token(object):
  29. def __init__(self, st, locn, tokString):
  30. self.tokenString = tokString
  31. self.locn = locn
  32. self.sourceLine = line(locn,st)
  33. self.lineNo = lineno(locn,st)
  34. self.col = col(locn,st)
  35. def __str__(self):
  36. return "%(tokenString)s (line: %(lineNo)d, col: %(col)d)" % self.__dict__
  37. def createTokenObject(st,locn,toks):
  38. return Token(st,locn, toks[0])
  39. wd = Word(alphas).setParseAction( createTokenObject )
  40. for tokenObj in OneOrMore(wd).parseString(data):
  41. print(tokenObj)