[Python-modules-commits] [pyparsing] 01/03: Import pyparsing_2.1.1+dfsg1.orig.tar.gz
Barry Warsaw
barry at moszumanska.debian.org
Fri May 6 18:13:10 UTC 2016
This is an automated email from the git hooks/post-receive script.
barry pushed a commit to branch master
in repository pyparsing.
commit 022befb36aafa07524e358d2f1efb838d90a5ee5
Author: Barry Warsaw <barry at python.org>
Date: Fri May 6 12:15:39 2016 -0500
Import pyparsing_2.1.1+dfsg1.orig.tar.gz
---
CHANGES | 188 +-
MANIFEST.in | 7 +
PKG-INFO | 9 +-
README | 10 +-
examples/chemicalFormulas.py | 6 +-
examples/datetimeParseActions.py | 24 +-
examples/deltaTime.py | 114 +-
examples/eval_arith.py | 12 +-
examples/excelExpr.py | 38 +-
examples/fourFn.py | 29 +-
examples/idlParse.py | 2 +-
examples/invRegex.py | 29 +-
examples/jsonParser.py | 2 +-
examples/listAllMatches.py | 34 +-
examples/lucene_grammar.py | 8 +-
examples/macroExpander.py | 7 +-
examples/mozillaCalendarParser.py | 5 +-
examples/oc.py | 6 +-
examples/parseListString.py | 42 +-
examples/parseTabularData.py | 50 +
examples/pgn.py | 6 +-
examples/protobuf_parser.py | 9 +-
examples/rangeCheck.py | 54 +-
examples/romanNumerals.py | 13 +-
examples/searchParserAppDemo.py | 2 +-
examples/searchparser.py | 109 +-
examples/select_parser.py | 3 +-
examples/simpleArith.py | 12 +-
examples/simpleSQL.py | 14 +-
examples/verilogParse.py | 2 +-
examples/wordsToNum.py | 27 +-
htmldoc/api-objects.txt | 5301 ++++-----
htmldoc/class-tree.html | 117 +-
htmldoc/frames.html | 2 +-
htmldoc/help.html | 6 +-
htmldoc/identifier-index.html | 1503 +--
htmldoc/index.html | 2 +-
htmldoc/module-tree.html | 8 +-
...pyparsing-module.html => pyparsing-module.html} | 413 +-
...g.pyparsing-pysrc.html => pyparsing-pysrc.html} | 11650 ++++++++++---------
...ing.And-class.html => pyparsing.And-class.html} | 173 +-
...s.html => pyparsing.CaselessKeyword-class.html} | 173 +-
...s.html => pyparsing.CaselessLiteral-class.html} | 163 +-
...-class.html => pyparsing.CharsNotIn-class.html} | 161 +-
...ine-class.html => pyparsing.Combine-class.html} | 165 +-
...g.Dict-class.html => pyparsing.Dict-class.html} | 159 +-
...g.Each-class.html => pyparsing.Each-class.html} | 171 +-
...Empty-class.html => pyparsing.Empty-class.html} | 151 +-
...-class.html => pyparsing.FollowedBy-class.html} | 157 +-
...ard-class.html => pyparsing.Forward-class.html} | 183 +-
...-class.html => pyparsing.GoToColumn-class.html} | 163 +-
...Group-class.html => pyparsing.Group-class.html} | 166 +-
...ord-class.html => pyparsing.Keyword-class.html} | 177 +-
...End-class.html => pyparsing.LineEnd-class.html} | 157 +-
...t-class.html => pyparsing.LineStart-class.html} | 163 +-
...ral-class.html => pyparsing.Literal-class.html} | 159 +-
...-class.html => pyparsing.MatchFirst-class.html} | 173 +-
...tch-class.html => pyparsing.NoMatch-class.html} | 157 +-
...tAny-class.html => pyparsing.NotAny-class.html} | 161 +-
...e-class.html => pyparsing.OneOrMore-class.html} | 205 +-
...ce-class.html => pyparsing.OnlyOnce-class.html} | 30 +-
...al-class.html => pyparsing.Optional-class.html} | 174 +-
...rsing.Or-class.html => pyparsing.Or-class.html} | 173 +-
...tml => pyparsing.ParseBaseException-class.html} | 50 +-
...ml => pyparsing.ParseElementEnhance-class.html} | 189 +-
...ss.html => pyparsing.ParseException-class.html} | 31 +-
...s.html => pyparsing.ParseExpression-class.html} | 195 +-
...ml => pyparsing.ParseFatalException-class.html} | 33 +-
...lass.html => pyparsing.ParseResults-class.html} | 158 +-
...l => pyparsing.ParseSyntaxException-class.html} | 45 +-
...ass.html => pyparsing.ParserElement-class.html} | 393 +-
...lass.html => pyparsing.QuotedString-class.html} | 167 +-
...pyparsing.RecursiveGrammarException-class.html} | 32 +-
...Regex-class.html => pyparsing.Regex-class.html} | 158 +-
...l => pyparsing.Regex.compiledREtype-class.html} | 294 +-
...ipTo-class.html => pyparsing.SkipTo-class.html} | 184 +-
...d-class.html => pyparsing.StringEnd-class.html} | 157 +-
...class.html => pyparsing.StringStart-class.html} | 157 +-
...ss-class.html => pyparsing.Suppress-class.html} | 158 +-
...Empty-class.html => pyparsing.Token-class.html} | 166 +-
...ss.html => pyparsing.TokenConverter-class.html} | 153 +-
...White-class.html => pyparsing.White-class.html} | 163 +-
...g.Word-class.html => pyparsing.Word-class.html} | 167 +-
...End-class.html => pyparsing.WordEnd-class.html} | 157 +-
...t-class.html => pyparsing.WordStart-class.html} | 157 +-
...-class.html => pyparsing.ZeroOrMore-class.html} | 205 +-
htmldoc/pyparsing.pyparsing.OneOrMore-class.html | 423 -
...rsing.pyparsing.Regex.compiledREtype-class.html | 167 -
htmldoc/pyparsing.pyparsing.Token-class.html | 365 -
htmldoc/pyparsing.pyparsing.Upcase-class.html | 368 -
htmldoc/pyparsing_2.0.2_docs.zip | Bin 330538 -> 0 bytes
htmldoc/redirect.html | 2 +-
htmldoc/toc-everything.html | 211 +-
...rsing-module.html => toc-pyparsing-module.html} | 207 +-
htmldoc/toc.html | 4 +-
PKG-INFO => pyparsing.egg-info/PKG-INFO | 9 +-
pyparsing.egg-info/SOURCES.txt | 173 +
pyparsing.egg-info/dependency_links.txt | 1 +
pyparsing.egg-info/top_level.txt | 1 +
pyparsing.py | 651 +-
setup.cfg | 11 +
setup.py | 7 +-
102 files changed, 14633 insertions(+), 15125 deletions(-)
diff --git a/CHANGES b/CHANGES
index 2fe5905..2a2bd57 100644
--- a/CHANGES
+++ b/CHANGES
@@ -2,8 +2,188 @@
Change Log
==========
-Version 2.0.3 -
----------------------------
+Version 2.1.1 -
+------------------------------
+- Added support for assigning to ParseResults using slices.
+
+- Fixed bug in ParseResults.toDict(), in which dict values were always
+ converted to dicts, even if they were just unkeyed lists of tokens.
+ Reported on SO by Gerald Thibault, thanks Gerald!
+
+- Fixed bug in SkipTo when using failOn, reported by robyschek, thanks!
+
+- Fixed bug in Each introduced in 2.1.0, reported by AND patch and
+ unit test submitted by robyschek, well done!
+
+- Removed use of functools.partial in replaceWith, as this creates
+ an ambiguous signature for the generated parse action, which fails in
+ PyPy. Reported by Evan Hubinger, thanks Evan!
+
+- Added default behavior to QuotedString to convert embedded '\t', '\n',
+ etc. characters to their whitespace counterparts. Found during Q&A
+ exchange on SO with Maxim.
+
+
+Version 2.1.0 - February, 2016
+------------------------------
+- Modified the internal _trim_arity method to distinguish between
+ TypeError's raised while trying to determine parse action arity and
+ those raised within the parse action itself. This will clear up those
+ confusing "<lambda>() takes exactly 1 argument (0 given)" error
+ messages when there is an actual TypeError in the body of the parse
+ action. Thanks to all who have raised this issue in the past, and
+ most recently to Michael Cohen, who sent in a proposed patch, and got
+ me to finally tackle this problem.
+
+- Added compatibility for pickle protocols 2-4 when pickling ParseResults.
+ In Python 2.x, protocol 0 was the default, and protocol 2 did not work.
+ In Python 3.x, protocol 3 is the default, so explicitly naming
+ protocol 0 or 1 was required to pickle ParseResults. With this release,
+ all protocols 0-4 are supported. Thanks for reporting this on StackOverflow,
+ Arne Wolframm, and for providing a nice simple test case!
+
+- Added optional 'stopOn' argument to ZeroOrMore and OneOrMore, to
+ simplify breaking on stop tokens that would match the repetition
+ expression.
+
+ It is a common problem to fail to look ahead when matching repetitive
+ tokens if the sentinel at the end also matches the repetition
+ expression, as when parsing "BEGIN aaa bbb ccc END" with:
+
+ "BEGIN" + OneOrMore(Word(alphas)) + "END"
+
+ Since "END" matches the repetition expression "Word(alphas)", it will
+ never get parsed as the terminating sentinel. Up until now, this has
+ to be resolved by the user inserting their own negative lookahead:
+
+ "BEGIN" + OneOrMore(~Literal("END") + Word(alphas)) + "END"
+
+ Using stopOn, they can more easily write:
+
+ "BEGIN" + OneOrMore(Word(alphas), stopOn="END") + "END"
+
+ The stopOn argument can be a literal string or a pyparsing expression.
+ Inspired by a question by Lamakaha on StackOverflow (and many previous
+ questions with the same negative-lookahead resolution).
+
+- Added expression names for many internal and builtin expressions, to
+ reduce name and error message overhead during parsing.
+
+- Converted helper lambdas to functions to refactor and add docstring
+ support.
+
+- Fixed ParseResults.asDict() to correctly convert nested ParseResults
+ values to dicts.
+
+- Cleaned up some examples, fixed typo in fourFn.py identified by
+ aristotle2600 on reddit.
+
+- Removed keepOriginalText helper method, which was deprecated ages ago.
+ Superceded by originalTextFor.
+
+- Same for the Upcase class, which was long ago deprecated and replaced
+ with the upcaseTokens method.
+
+
+
+Version 2.0.7 - December, 2015
+------------------------------
+- Simplified string representation of Forward class, to avoid memory
+ and performance errors while building ParseException messages. Thanks,
+ Will McGugan, Andrea Censi, and Martijn Vermaat for the bug reports and
+ test code.
+
+- Cleaned up additional issues from enhancing the error messages for
+ Or and MatchFirst, handling Unicode values in expressions. Fixes Unicode
+ encoding issues in Python 2, thanks to Evan Hubinger for the bug report.
+
+- Fixed implementation of dir() for ParseResults - was leaving out all the
+ defined methods and just adding the custom results names.
+
+- Fixed bug in ignore() that was introduced in pyparsing 1.5.3, that would
+ not accept a string literal as the ignore expression.
+
+- Added new example parseTabularData.py to illustrate parsing of data
+ formatted in columns, with detection of empty cells.
+
+- Updated a number of examples to more current Python and pyparsing
+ forms.
+
+
+Version 2.0.6 - November, 2015
+------------------------------
+- Fixed a bug in Each when multiple Optional elements are present.
+ Thanks for reporting this, whereswalden on SO.
+
+- Fixed another bug in Each, when Optional elements have results names
+ or parse actions, reported by Max Rothman - thank you, Max!
+
+- Added optional parseAll argument to runTests, whether tests should
+ require the entire input string to be parsed or not (similar to
+ parseAll argument to parseString). Plus a little neaten-up of the
+ output on Python 2 (no stray ()'s).
+
+- Modified exception messages from MatchFirst and Or expressions. These
+ were formerly misleading as they would only give the first or longest
+ exception mismatch error message. Now the error message includes all
+ the alternatives that were possible matches. Originally proposed by
+ a pyparsing user, but I've lost the email thread - finally figured out
+ a fairly clean way to do this.
+
+- Fixed a bug in Or, when a parse action on an alternative raises an
+ exception, other potentially matching alternatives were not always tried.
+ Reported by TheVeryOmni on the pyparsing wiki, thanks!
+
+- Fixed a bug to dump() introduced in 2.0.4, where list values were shown
+ in duplicate.
+
+
+Version 2.0.5 - October, 2015
+-----------------------------
+- (&$(@#&$(@!!!! Some "print" statements snuck into pyparsing v2.0.4,
+ breaking Python 3 compatibility! Fixed. Reported by jenshn, thanks!
+
+
+Version 2.0.4 - October, 2015
+-----------------------------
+- Added ParserElement.addCondition, to simplify adding parse actions
+ that act primarily as filters. If the given condition evaluates False,
+ pyparsing will raise a ParseException. The condition should be a method
+ with the same method signature as a parse action, but should return a
+ boolean. Suggested by Victor Porton, nice idea Victor, thanks!
+
+- Slight mod to srange to accept unicode literals for the input string,
+ such as "[а-яА-Я]" instead of "[\u0430-\u044f\u0410-\u042f]". Thanks
+ to Alexandr Suchkov for the patch!
+
+- Enhanced implementation of replaceWith.
+
+- Fixed enhanced ParseResults.dump() method when the results consists
+ only of an unnamed array of sub-structure results. Reported by Robin
+ Siebler, thanks for your patience and persistence, Robin!
+
+- Fixed bug in fourFn.py example code, where pi and e were defined using
+ CaselessLiteral instead of CaselessKeyword. This was not a problem until
+ adding a new function 'exp', and the leading 'e' of 'exp' was accidentally
+ parsed as the mathematical constant 'e'. Nice catch, Tom Grydeland - thanks!
+
+- Adopt new-fangled Python features, like decorators and ternary expressions,
+ per suggestions from Williamzjc - thanks William! (Oh yeah, I'm not
+ supporting Python 2.3 with this code any more...) Plus, some additional
+ code fixes/cleanup - thanks again!
+
+- Added ParserElement.runTests, a little test bench for quickly running
+ an expression against a list of sample input strings. Basically, I got
+ tired of writing the same test code over and over, and finally added it
+ as a test point method on ParserElement.
+
+- Added withClass helper method, a simplified version of withAttribute for
+ the common but annoying case when defining a filter on a div's class -
+ made difficult because 'class' is a Python reserved word.
+
+
+Version 2.0.3 - October, 2014
+-----------------------------
- Fixed escaping behavior in QuotedString. Formerly, only quotation
marks (or characters designated as quotation marks in the QuotedString
constructor) would be escaped. Now all escaped characters will be
@@ -719,7 +899,7 @@ Version 1.4.8 - October, 2007
the new features.
- Added performance speedup to grammars using operatorPrecedence,
- instigated by Stefan Reich�r - thanks for the feedback, Stefan!
+ instigated by Stefan Reichör - thanks for the feedback, Stefan!
- Fixed bug/typo when deleting an element from a ParseResults by
using the element's results name.
@@ -1414,7 +1594,7 @@ Version 1.3 - March, 2005
(Big thanks to Gavin Panella!)
- Added constant alphas8bit to include the following 8-bit characters:
- �������������������������������������������������������������
+ ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ
- Added srange() function to simplify definition of Word elements, using
regexp-like '[A-Za-z0-9]' syntax. This also simplifies referencing
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..5f2b98b
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,7 @@
+include pyparsing.py
+include HowToUsePyparsing.html pyparsingClassDiagram.*
+include README CHANGES LICENSE
+include examples/*.py examples/Setup.ini examples/*.dfm examples/*.ics examples/*.html
+include htmldoc/*.*
+include docs/*.*
+include robots.txt
diff --git a/PKG-INFO b/PKG-INFO
index 4c106d1..9dfc8e8 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,6 +1,6 @@
-Metadata-Version: 1.0
+Metadata-Version: 1.1
Name: pyparsing
-Version: 2.0.3
+Version: 2.1.1
Summary: Python parsing module
Home-page: http://pyparsing.wikispaces.com/
Author: Paul McGuire
@@ -18,7 +18,6 @@ Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
-Classifier: Programming Language :: Python :: 3.0
-Classifier: Programming Language :: Python :: 3.1
-Classifier: Programming Language :: Python :: 3.2
Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: 3.5
diff --git a/README b/README
index 44dd51f..dc959ec 100644
--- a/README
+++ b/README
@@ -50,7 +50,15 @@ Do the usual:
python setup.py install
-(pyparsing requires Python 2.3.2 or later.)
+(pyparsing requires Python 2.6 or later.)
+
+Or corresponding commands using pip, easy_install, or wheel:
+
+ pip install pyparsing
+
+ easy_install pyparsing
+
+ wheel install pyparsing
Documentation
diff --git a/examples/chemicalFormulas.py b/examples/chemicalFormulas.py
index e7d7757..ce66afd 100644
--- a/examples/chemicalFormulas.py
+++ b/examples/chemicalFormulas.py
@@ -37,7 +37,7 @@ element = Word( alphas.upper(), alphas.lower(), max=2)
elementRef = Group( element + Optional( Word( digits ), default="1" ) )
formula = OneOrMore( elementRef )
-fn = lambda elemList : sum( [ atomicWeight[elem]*int(qty) for elem,qty in elemList ] )
+fn = lambda elemList : sum(atomicWeight[elem]*int(qty) for elem,qty in elemList)
test( formula, "H2O", fn )
test( formula, "C6H5OH", fn )
test( formula, "NaCl", fn )
@@ -47,7 +47,7 @@ print()
elementRef = Group( element("symbol") + Optional( Word( digits ), default="1" )("qty") )
formula = OneOrMore( elementRef )
-fn = lambda elemList : sum( [ atomicWeight[elem.symbol]*int(elem.qty) for elem in elemList ] )
+fn = lambda elemList : sum(atomicWeight[elem.symbol]*int(elem.qty) for elem in elemList)
test( formula, "H2O", fn )
test( formula, "C6H5OH", fn )
test( formula, "NaCl", fn )
@@ -58,7 +58,7 @@ integer = Word( digits ).setParseAction(lambda t:int(t[0]))
elementRef = Group( element("symbol") + Optional( integer, default=1 )("qty") )
formula = OneOrMore( elementRef )
-fn = lambda elemList : sum( [ atomicWeight[elem.symbol]*elem.qty for elem in elemList ] )
+fn = lambda elemList : sum(atomicWeight[elem.symbol]*elem.qty for elem in elemList)
test( formula, "H2O", fn )
test( formula, "C6H5OH", fn )
test( formula, "NaCl", fn )
diff --git a/examples/datetimeParseActions.py b/examples/datetimeParseActions.py
index 38e660e..26d96a3 100644
--- a/examples/datetimeParseActions.py
+++ b/examples/datetimeParseActions.py
@@ -10,7 +10,7 @@ from pyparsing import *
# define an integer string, and a parse action to convert it
# to an integer at parse time
-integer = Word(nums)
+integer = Word(nums).setName("integer")
def convertToInt(tokens):
# no need to test for validity - we can't get here
# unless tokens[0] contains all numeric digits
@@ -20,28 +20,24 @@ integer.setParseAction(convertToInt)
#integer = Word(nums).setParseAction(lambda t: int(t[0]))
# define a pattern for a year/month/day date
-date = integer('year') + '/' + integer('month') + '/' + integer('day')
+date_expr = integer('year') + '/' + integer('month') + '/' + integer('day')
def convertToDatetime(s,loc,tokens):
try:
# note that the year, month, and day fields were already
# converted to ints from strings by the parse action defined
# on the integer expression above
- return datetime(tokens.year, tokens.month, tokens.day)
+ return datetime(tokens.year, tokens.month, tokens.day).date()
except Exception as ve:
errmsg = "'%d/%d/%d' is not a valid date, %s" % \
(tokens.year, tokens.month, tokens.day, ve)
raise ParseException(s, loc, errmsg)
-date.setParseAction(convertToDatetime)
+date_expr.setParseAction(convertToDatetime)
-def test(s):
- try:
- print(date.parseString(s))
- except ParseException as pe:
- print(pe)
-
-test("2000/1/1")
-test("2000/13/1") # invalid month
-test("1900/2/29") # 1900 was not a leap year
-test("2000/2/29") # but 2000 was
+date_expr.runTests("""\
+ 2000/1/1
+ 2000/13/1 # invalid month
+ 1900/2/29 # 1900 was not a leap year
+ 2000/2/29 # but 2000 was
+ """)
\ No newline at end of file
diff --git a/examples/deltaTime.py b/examples/deltaTime.py
index 02539e6..a63b19e 100644
--- a/examples/deltaTime.py
+++ b/examples/deltaTime.py
@@ -110,11 +110,17 @@ ago = CL("ago").setParseAction(replaceWith(-1))
next_ = CL("next").setParseAction(replaceWith(1))
last_ = CL("last").setParseAction(replaceWith(-1))
at_ = CL("at")
+on_ = CL("on")
couple = (Optional(CL("a")) + CL("couple") + Optional(CL("of"))).setParseAction(replaceWith(2))
a_qty = CL("a").setParseAction(replaceWith(1))
integer = Word(nums).setParseAction(lambda t:int(t[0]))
int4 = Group(Word(nums,exact=4).setParseAction(lambda t: [int(t[0][:2]),int(t[0][2:])] ))
+def fill_timefields(t):
+ t[0]['HH'] = t[0][0]
+ t[0]['MM'] = t[0][1]
+ t[0]['ampm'] = ('am','pm')[t[0].HH >= 12]
+int4.addParseAction(fill_timefields)
qty = integer | couple | a_qty
dayName = oneOf( list(calendar.day_name) )
@@ -132,13 +138,15 @@ dayTimeSpec.setParseAction(calculateTime)
relativeTimeUnit = (week | day | hour | minute | second)
-timespec = Group(int4("miltime") |
+timespec = Group(ungroup(int4) |
integer("HH") +
- Optional(COLON + integer("MM")) +
- Optional(COLON + integer("SS")) + (am | pm)("ampm")
+ ungroup(Optional(COLON + integer,[0]))("MM") +
+ ungroup(Optional(COLON + integer,[0]))("SS") +
+ (am | pm)("ampm")
)
+
absTimeSpec = ((noon | midnight | now | timespec("timeparts"))("timeOfDay") +
- Optional(dayRef)("dayRef") |
+ Optional(on_) + Optional(dayRef)("dayRef") |
dayRef("dayRef") + at_ +
(noon | midnight | now | timespec("timeparts"))("timeOfDay"))
absTimeSpec.setParseAction(convertToAbsTime,calculateTime)
@@ -155,51 +163,53 @@ nlTimeExpression = (absTimeSpec + Optional(dayTimeSpec) |
dayTimeSpec + Optional(Optional(at_) + absTimeSpec) |
relTimeSpec + Optional(absTimeSpec))
-# test grammar
-tests = """\
-today
-tomorrow
-yesterday
-in a couple of days
-a couple of days from now
-a couple of days from today
-in a day
-3 days ago
-3 days from now
-a day ago
-in 2 weeks
-in 3 days at 5pm
-now
-10 minutes ago
-10 minutes from now
-in 10 minutes
-in a minute
-in a couple of minutes
-20 seconds ago
-in 30 seconds
-20 seconds before noon
-20 seconds before noon tomorrow
-noon
-midnight
-noon tomorrow
-6am tomorrow
-0800 yesterday
-12:15 AM today
-3pm 2 days from today
-a week from today
-a week from now
-3 weeks ago
-noon next Sunday
-noon Sunday
-noon last Sunday
-2pm next Sunday
-next Sunday at 2pm""".splitlines()
-
-for t in tests:
- print(t, "(relative to %s)" % datetime.now())
- res = nlTimeExpression.parseString(t)
- if "calculatedTime" in res:
- print(res.calculatedTime)
- else:
- print("???")
- print()
+if __name__ == "__main__":
+ # test grammar
+ tests = """\
+ today
+ tomorrow
+ yesterday
+ in a couple of days
+ a couple of days from now
+ a couple of days from today
+ in a day
+ 3 days ago
+ 3 days from now
+ a day ago
+ in 2 weeks
+ in 3 days at 5pm
+ now
+ 10 minutes ago
+ 10 minutes from now
+ in 10 minutes
+ in a minute
+ in a couple of minutes
+ 20 seconds ago
+ in 30 seconds
+ 20 seconds before noon
+ 20 seconds before noon tomorrow
+ noon
+ midnight
+ noon tomorrow
+ 6am tomorrow
+ 0800 yesterday
+ 12:15 AM today
+ 3pm 2 days from today
+ a week from today
+ a week from now
+ 3 weeks ago
+ noon next Sunday
+ noon Sunday
+ noon last Sunday
+ 2pm next Sunday
+ next Sunday at 2pm""".splitlines()
+
+ for t in tests:
+ t = t.strip()
+ print(t, "(relative to %s)" % datetime.now())
+ res = nlTimeExpression.parseString(t)
+ if "calculatedTime" in res:
+ print(res.calculatedTime)
+ else:
+ print("???")
+ print('')
diff --git a/examples/eval_arith.py b/examples/eval_arith.py
index 85566c7..9562253 100644
--- a/examples/eval_arith.py
+++ b/examples/eval_arith.py
@@ -9,7 +9,7 @@
# operands
#
from pyparsing import Word, nums, alphas, Combine, oneOf, \
- opAssoc, operatorPrecedence, Literal
+ opAssoc, infixNotation, Literal
class EvalConstant(object):
"Class to evaluate a parsed constant or variable"
@@ -120,7 +120,7 @@ expop = Literal('**')
# use parse actions to attach EvalXXX constructors to sub-expressions
operand.setParseAction(EvalConstant)
-arith_expr = operatorPrecedence(operand,
+arith_expr = infixNotation(operand,
[
(signop, 1, opAssoc.RIGHT, EvalSignOp),
(expop, 2, opAssoc.LEFT, EvalPowerOp),
@@ -129,7 +129,7 @@ arith_expr = operatorPrecedence(operand,
])
comparisonop = oneOf("< <= > >= != = <> LT GT LE GE EQ NE")
-comp_expr = operatorPrecedence(arith_expr,
+comp_expr = infixNotation(arith_expr,
[
(comparisonop, 2, opAssoc.LEFT, EvalComparisonOp),
])
@@ -210,14 +210,14 @@ def main():
for test,expected in tests:
ret = comp_expr.parseString(test)[0]
parsedvalue = ret.eval()
- print(test, expected, parsedvalue, end=' ')
+ print(test, expected, parsedvalue)
if parsedvalue != expected:
print("<<< FAIL")
failed += 1
else:
- print()
+ print('')
- print()
+ print('')
if failed:
print(failed, "tests FAILED")
else:
diff --git a/examples/excelExpr.py b/examples/excelExpr.py
index 0d0c06a..2700100 100644
--- a/examples/excelExpr.py
+++ b/examples/excelExpr.py
@@ -6,8 +6,9 @@
#
from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
alphanums, nums, Optional, Group, oneOf, Forward, Regex,
- operatorPrecedence, opAssoc, dblQuotedString, delimitedList,
- Combine, Literal, QuotedString)
+ infixNotation, opAssoc, dblQuotedString, delimitedList,
+ Combine, Literal, QuotedString, ParserElement)
+ParserElement.enablePackrat()
EQ,EXCL,LPAR,RPAR,COLON,COMMA = map(Suppress, '=!():,')
EXCL, DOLLAR = map(Literal,"!$")
@@ -28,10 +29,10 @@ condExpr = expr + COMPARISON_OP + expr
ifFunc = (CaselessKeyword("if") +
LPAR +
Group(condExpr)("condition") +
- COMMA + expr("if_true") +
- COMMA + expr("if_false") + RPAR)
+ COMMA + Group(expr)("if_true") +
+ COMMA + Group(expr)("if_false") + RPAR)
-statFunc = lambda name : CaselessKeyword(name) + LPAR + delimitedList(expr) + RPAR
+statFunc = lambda name : Group(CaselessKeyword(name) + Group(LPAR + delimitedList(expr) + RPAR))
sumFunc = statFunc("sum")
minFunc = statFunc("min")
maxFunc = statFunc("max")
@@ -42,31 +43,26 @@ multOp = oneOf("* /")
addOp = oneOf("+ -")
numericLiteral = Regex(r"\-?\d+(\.\d+)?")
operand = numericLiteral | funcCall | cellRange | cellRef
-arithExpr = operatorPrecedence(operand,
+arithExpr = infixNotation(operand,
[
(multOp, 2, opAssoc.LEFT),
(addOp, 2, opAssoc.LEFT),
])
textOperand = dblQuotedString | cellRef
-textExpr = operatorPrecedence(textOperand,
+textExpr = infixNotation(textOperand,
[
('&', 2, opAssoc.LEFT),
])
-expr << (arithExpr | textExpr)
+expr << (arithExpr | textExpr)
-test1 = "=3*A7+5"
-test2 = "=3*Sheet1!$A$7+5"
-test2a ="=3*'Sheet 1'!$A$7+5"
-test2b ="=3*'O''Reilly''s sheet'!$A$7+5"
-test3 = "=if(Sum(A1:A25)>42,Min(B1:B25), " \
- "if(Sum(C1:C25)>3.14, (Min(C1:C25)+3)*18,Max(B1:B25)))"
-test3a = "=sum(a1:a25,10,min(b1,c2,d3))"
-import pprint
-tests = [locals()[t] for t in list(locals().keys()) if t.startswith("test")]
-for test in tests:
- print(test)
- pprint.pprint( (EQ + expr).parseString(test,parseAll=True).asList() )
- print()
+(EQ + expr).runTests("""\
+ =3*A7+5"
+ =3*Sheet1!$A$7+5"
+ =3*'Sheet 1'!$A$7+5"
+ =3*'O''Reilly''s sheet'!$A$7+5"
+ =if(Sum(A1:A25)>42,Min(B1:B25),if(Sum(C1:C25)>3.14, (Min(C1:C25)+3)*18,Max(B1:B25)))"
+ =sum(a1:a25,10,min(b1,c2,d3))
+""")
\ No newline at end of file
diff --git a/examples/fourFn.py b/examples/fourFn.py
index 8ea4609..75f3909 100644
--- a/examples/fourFn.py
+++ b/examples/fourFn.py
@@ -10,7 +10,8 @@
# Copyright 2003-2009 by Paul McGuire
#
from pyparsing import Literal,CaselessLiteral,Word,Group,Optional,\
- ZeroOrMore,Forward,nums,alphas,Regex,ParseException
+ ZeroOrMore,Forward,nums,alphas,alphanums,Regex,ParseException,\
+ CaselessKeyword, Suppress
import math
import operator
@@ -42,23 +43,22 @@ def BNF():
global bnf
if not bnf:
point = Literal( "." )
- e = CaselessLiteral( "E" )
+ # use CaselessKeyword for e and pi, to avoid accidentally matching
+ # functions that start with 'e' or 'pi' (such as 'exp'); Keyword
+ # and CaselessKeyword only match whole words
+ e = CaselessKeyword( "E" )
+ pi = CaselessKeyword( "PI" )
#~ fnumber = Combine( Word( "+-"+nums, nums ) +
#~ Optional( point + Optional( Word( nums ) ) ) +
#~ Optional( e + Word( "+-"+nums, nums ) ) )
- fnumber = Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
- ident = Word(alphas, alphas+nums+"_$")
+ fnumber = Regex(r"[+-]?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?")
+ ident = Word(alphas, alphanums+"_$")
- plus = Literal( "+" )
- minus = Literal( "-" )
- mult = Literal( "*" )
- div = Literal( "/" )
- lpar = Literal( "(" ).suppress()
- rpar = Literal( ")" ).suppress()
+ plus, minus, mult, div = map(Literal, "+-*/")
+ lpar, rpar = map(Suppress, "()")
addop = plus | minus
multop = mult | div
expop = Literal( "^" )
- pi = CaselessLiteral( "PI" )
expr = Forward()
atom = ((0,None)*minus + ( pi | e | fnumber | ident + lpar + expr + rpar | ident ).setParseAction( pushFirst ) |
@@ -84,6 +84,7 @@ opn = { "+" : operator.add,
fn = { "sin" : math.sin,
"cos" : math.cos,
"tan" : math.tan,
+ "exp" : math.exp,
"abs" : abs,
"trunc" : lambda a: int(a),
"round" : round,
@@ -111,7 +112,7 @@ if __name__ == "__main__":
def test( s, expVal ):
global exprStack
- exprStack = []
+ exprStack[:] = []
try:
results = BNF().parseString( s, parseAll=True )
val = evaluateStack( exprStack[:] )
@@ -149,13 +150,15 @@ if __name__ == "__main__":
test( "round(E)", round(math.e) )
test( "round(-E)", round(-math.e) )
test( "E^PI", math.e**math.pi )
+ test( "exp(0)", 1 )
+ test( "exp(1)", math.e )
test( "2^3^2", 2**3**2 )
test( "2^3+2", 2**3+2 )
test( "2^3+5", 2**3+5 )
test( "2^9", 2**9 )
test( "sgn(-2)", -1 )
test( "sgn(0)", 0 )
- test( "foo(0.1)", 1 )
+ test( "foo(0.1)", None )
test( "sgn(0.1)", 1 )
diff --git a/examples/idlParse.py b/examples/idlParse.py
index 419e56f..dd556e5 100644
--- a/examples/idlParse.py
+++ b/examples/idlParse.py
@@ -6,7 +6,7 @@
# Copyright (c) 2003, Paul McGuire
#
-from pyparsing import Literal, CaselessLiteral, Word, Upcase, OneOrMore, ZeroOrMore, \
+from pyparsing import Literal, CaselessLiteral, Word, OneOrMore, ZeroOrMore, \
Forward, NotAny, delimitedList, oneOf, Group, Optional, Combine, alphas, nums, restOfLine, cStyleComment, \
alphanums, printables, empty, quotedString, ParseException, ParseResults, Keyword, Regex
import pprint
diff --git a/examples/invRegex.py b/examples/invRegex.py
index 965fe8f..5d9a393 100644
--- a/examples/invRegex.py
+++ b/examples/invRegex.py
@@ -14,7 +14,7 @@
__all__ = ["count","invert"]
from pyparsing import (Literal, oneOf, printables, ParserElement, Combine,
- SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
+ SkipTo, infixNotation, ParseFatalException, Word, nums, opAssoc,
Suppress, ParseResults, srange)
class CharacterRangeEmitter(object):
@@ -150,7 +150,7 @@ def parser():
global _parser
if _parser is None:
ParserElement.setDefaultWhitespaceChars("")
- lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")
+ lbrack,rbrack,lbrace,rbrace,lparen,rparen,colon,qmark = map(Literal,"[]{}():?")
reMacro = Combine("\\" + oneOf(list("dws")))
escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
@@ -158,6 +158,7 @@ def parser():
reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
+ reNonCaptureGroup = Suppress("?:")
reDot = Literal(".")
repetition = (
( lbrace + Word(nums).setResultsName("count") + rbrace ) |
@@ -170,8 +171,8 @@ def parser():
reMacro.setParseAction(handleMacro)
reDot.setParseAction(handleDot)
- reTerm = ( reLiteral | reRange | reMacro | reDot )
- reExpr = operatorPrecedence( reTerm,
+ reTerm = ( reLiteral | reRange | reMacro | reDot | reNonCaptureGroup)
+ reExpr = infixNotation( reTerm,
[
(repetition, 1, opAssoc.LEFT, handleRepetition),
(None, 2, opAssoc.LEFT, handleSequence),
@@ -184,10 +185,7 @@ def parser():
def count(gen):
"""Simple function to count the number of elements returned by a generator."""
- i = 0
- for s in gen:
- i += 1
- return i
+ return sum(1 for _ in gen)
def invert(regex):
"""Call this routine as a generator to return all the strings that
@@ -212,6 +210,7 @@ def main():
fooba[rz]{2}
(foobar){2}
([01]\d)|(2[0-5])
+ (?:[01]\d)|(2[0-5])
([01]\d\d)|(2[0-4]\d)|(25[0-5])
[A-C]{1,2}
[A-C]{0,3}
@@ -229,6 +228,9 @@ def main():
A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
(a|b)|(x|y)
(a|b) (x|y)
+ [ABCDEFG](?:#|##|b|bb)?(?:maj|min|m|sus|aug|dim)?[0-9]?(?:/[ABCDEFG](?:#|##|b|bb)?)?
+ (Fri|Mon|S(atur|un)|T(hur|ue)s|Wednes)day
+ A(pril|ugust)|((Dec|Nov|Sept)em|Octo)ber|(Febr|Jan)uary|Ju(ly|ne)|Ma(rch|y)
""".split('\n')
for t in tests:
@@ -237,14 +239,19 @@ def main():
print('-'*50)
print(t)
try:
- print(count(invert(t)))
+ num = count(invert(t))
+ print(num)
+ maxprint = 30
for s in invert(t):
print(s)
+ maxprint -= 1
+ if not maxprint:
+ break
except ParseFatalException as pfe:
print(pfe.msg)
- print()
+ print('')
continue
- print()
+ print('')
if __name__ == "__main__":
main()
diff --git a/examples/jsonParser.py b/examples/jsonParser.py
index 5149b22..45cdef3 100644
--- a/examples/jsonParser.py
+++ b/examples/jsonParser.py
@@ -45,7 +45,7 @@ jsonNumber = Combine( Optional('-') + ( '0' | Word('123456789',nums) ) +
jsonObject = Forward()
jsonValue = Forward()
jsonElements = delimitedList( jsonValue )
-jsonArray = Group(Suppress('[') + Optional(jsonElements) + Suppress(']') )
+jsonArray = Group(Suppress('[') + Optional(jsonElements, []) + Suppress(']') )
jsonValue << ( jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL )
memberDef = Group( jsonString + Suppress(':') + jsonValue )
jsonMembers = delimitedList( memberDef )
diff --git a/examples/listAllMatches.py b/examples/listAllMatches.py
index 43f998b..1b1bdd4 100644
--- a/examples/listAllMatches.py
+++ b/examples/listAllMatches.py
@@ -12,13 +12,13 @@ nonAlphas = [ c for c in printables if not c.isalpha() ]
print("Extract vowels, consonants, and special characters from this test string:")
print("'" + test + "'")
-print()
+print('')
print("Define grammar using normal results names")
print("(only last matching symbol is saved)")
-vowels = oneOf(list("aeiouy"), caseless=True).setResultsName("vowels")
-cons = oneOf(list("bcdfghjklmnpqrstvwxz"), caseless=True).setResultsName("cons")
-other = oneOf(list(nonAlphas)).setResultsName("others")
+vowels = oneOf(list("aeiouy"), caseless=True)("vowels")
+cons = oneOf(list("bcdfghjklmnpqrstvwxz"), caseless=True)("cons")
+other = oneOf(nonAlphas)("others")
letters = OneOrMore(cons | vowels | other) + StringEnd()
results = letters.parseString(test)
@@ -26,27 +26,27 @@ print(results)
print(results.vowels)
print(results.cons)
print(results.others)
-print()
+print('')
print("Define grammar using results names, with listAllMatches=True")
print("(all matching symbols are saved)")
-vowels = oneOf(list("aeiouy"), caseless=True).setResultsName("vowels",listAllMatches=True)
-cons = oneOf(list("bcdfghjklmnpqrstvwxz"), caseless=True).setResultsName("cons",listAllMatches=True)
-other = oneOf(list(nonAlphas)).setResultsName("others",listAllMatches=True)
+vowels = oneOf(list("aeiouy"), caseless=True)("vowels*")
+cons = oneOf(list("bcdfghjklmnpqrstvwxz"), caseless=True)("cons*")
+other = oneOf(nonAlphas)("others*")
-letters = OneOrMore(cons | vowels | other) + StringEnd()
+letters = OneOrMore(cons | vowels | other)
-results = letters.parseString(test)
+results = letters.parseString(test, parseAll=True)
print(results)
-print(sorted(list(set(results))))
-print()
+print(sorted(set(results)))
+print('')
print(results.vowels)
-print(sorted(list(set(results.vowels))))
-print()
+print(sorted(set(results.vowels)))
+print('')
print(results.cons)
-print(sorted(list(set(results.cons))))
-print()
+print(sorted(set(results.cons)))
+print('')
print(results.others)
-print(sorted(list(set(results.others))))
+print(sorted(set(results.others)))
diff --git a/examples/lucene_grammar.py b/examples/lucene_grammar.py
index c098cce..179f25e 100644
--- a/examples/lucene_grammar.py
+++ b/examples/lucene_grammar.py
@@ -8,7 +8,7 @@
#
... 39889 lines suppressed ...
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/pyparsing.git
More information about the Python-modules-commits
mailing list