summaryrefslogtreecommitdiff
path: root/src/examples/linenoExample.py
diff options
context:
space:
mode:
authorPaul McGuire <ptmcg@austin.rr.com>2012-10-02 04:55:56 +0000
committerPaul McGuire <ptmcg@austin.rr.com>2012-10-02 04:55:56 +0000
commita7f9dda0668bfce4fba51df1bf2976b4a93a8bd5 (patch)
tree57ea8bcf2e66532a36c833a7bc57cff9d5d0e4dd /src/examples/linenoExample.py
parentf5d2b716ffb57b65660a7ee0bbf04332dfb29620 (diff)
downloadpyparsing-git-a7f9dda0668bfce4fba51df1bf2976b4a93a8bd5.tar.gz
Add example files to SVN
Diffstat (limited to 'src/examples/linenoExample.py')
-rw-r--r--src/examples/linenoExample.py49
1 files changed, 49 insertions, 0 deletions
diff --git a/src/examples/linenoExample.py b/src/examples/linenoExample.py
new file mode 100644
index 0000000..751822c
--- /dev/null
+++ b/src/examples/linenoExample.py
@@ -0,0 +1,49 @@
+#
+# linenoExample.py
+#
+# an example of using the location value returned by pyparsing to
+# extract the line and column number of the location of the matched text,
+# or to extract the entire line of text.
+#
+# Copyright (c) 2006, Paul McGuire
+#
+from pyparsing import *
+
+data = """Now is the time
+for all good men
+to come to the aid
+of their country."""
+
+# demonstrate use of lineno, line, and col in a parse action
+def reportLongWords(st,locn,toks):
+ word = toks[0]
+ if len(word) > 3:
+ print "Found '%s' on line %d at column %d" % (word, lineno(locn,st), col(locn,st))
+ print "The full line of text was:"
+ print "'%s'" % line(locn,st)
+ print (" "*col(locn,st))+" ^"
+ print
+
+wd = Word(alphas).setParseAction( reportLongWords )
+OneOrMore(wd).parseString(data)
+
+
+# demonstrate returning an object from a parse action, containing more information
+# than just the matching token text
+class Token(object):
+ def __init__(self, st, locn, tokString):
+ self.tokenString = tokString
+ self.locn = locn
+ self.sourceLine = line(locn,st)
+ self.lineNo = lineno(locn,st)
+ self.col = col(locn,st)
+ def __str__(self):
+ return "%(tokenString)s (line: %(lineNo)d, col: %(col)d)" % self.__dict__
+
+def createTokenObject(st,locn,toks):
+ return Token(st,locn, toks[0])
+
+wd = Word(alphas).setParseAction( createTokenObject )
+
+for tokenObj in OneOrMore(wd).parseString(data):
+ print tokenObj