summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorptmcg <ptmcg@9bf210a0-9d2d-494c-87cf-cfb32e7dff7b>2016-01-27 23:42:22 +0000
committerptmcg <ptmcg@9bf210a0-9d2d-494c-87cf-cfb32e7dff7b>2016-01-27 23:42:22 +0000
commit8294fbe3001448e19491426220453a92f4586c8d (patch)
tree3c763df22c93908c5d9004c018a5986d06f35646
parent58781833e130bd10c5854e12395cb00dab652962 (diff)
downloadpyparsing-8294fbe3001448e19491426220453a92f4586c8d.tar.gz
Cleanup examples, fix typo in fourFn.py, convert sample tests to use runTests
git-svn-id: svn://svn.code.sf.net/p/pyparsing/code/trunk@316 9bf210a0-9d2d-494c-87cf-cfb32e7dff7b
-rw-r--r--src/examples/excelExpr.py32
-rw-r--r--src/examples/fourFn.py19
-rw-r--r--src/examples/invRegex.py25
-rw-r--r--src/examples/rangeCheck.py15
4 files changed, 40 insertions, 51 deletions
diff --git a/src/examples/excelExpr.py b/src/examples/excelExpr.py
index 0d0c06a..39af365 100644
--- a/src/examples/excelExpr.py
+++ b/src/examples/excelExpr.py
@@ -7,7 +7,8 @@
from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
alphanums, nums, Optional, Group, oneOf, Forward, Regex,
operatorPrecedence, opAssoc, dblQuotedString, delimitedList,
- Combine, Literal, QuotedString)
+ 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")
@@ -53,20 +54,15 @@ textExpr = operatorPrecedence(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/src/examples/fourFn.py b/src/examples/fourFn.py
index 2b8c28b..75f3909 100644
--- a/src/examples/fourFn.py
+++ b/src/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,CaselessKeyword
+ ZeroOrMore,Forward,nums,alphas,alphanums,Regex,ParseException,\
+ CaselessKeyword, Suppress
import math
import operator
@@ -50,15 +51,11 @@ def BNF():
#~ 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( "^" )
@@ -115,7 +112,7 @@ if __name__ == "__main__":
def test( s, expVal ):
global exprStack
- exprStack = []
+ exprStack[:] = []
try:
results = BNF().parseString( s, parseAll=True )
val = evaluateStack( exprStack[:] )
@@ -161,7 +158,7 @@ if __name__ == "__main__":
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/src/examples/invRegex.py b/src/examples/invRegex.py
index 965fe8f..26d12ed 100644
--- a/src/examples/invRegex.py
+++ b/src/examples/invRegex.py
@@ -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,7 +171,7 @@ def parser():
reMacro.setParseAction(handleMacro)
reDot.setParseAction(handleDot)
- reTerm = ( reLiteral | reRange | reMacro | reDot )
+ reTerm = ( reLiteral | reRange | reMacro | reDot | reNonCaptureGroup)
reExpr = operatorPrecedence( reTerm,
[
(repetition, 1, opAssoc.LEFT, handleRepetition),
@@ -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/src/examples/rangeCheck.py b/src/examples/rangeCheck.py
index 59bd49c..67cf267 100644
--- a/src/examples/rangeCheck.py
+++ b/src/examples/rangeCheck.py
@@ -52,22 +52,11 @@ maxdate = datetime.now().date()
dateExpr = ranged_value(dateExpr, mindate, maxdate)
-tests = """
+dateExpr.runTests("""
2011/5/8
2001/1/1
2004/2/29
- 2004/2/30
2004/2
- 1999/12/31
- """.splitlines()
-for t in tests:
- t = t.strip()
- if not t: continue
- print(t)
- try:
- print(dateExpr.parseString(t)[0])
- except Exception as e:
- print(str(e))
- print('')
+ 1999/12/31""")