diff options
Diffstat (limited to 'examples')
76 files changed, 879 insertions, 919 deletions
diff --git a/examples/0README.html b/examples/0README.html index 303d44d..e566784 100644 --- a/examples/0README.html +++ b/examples/0README.html @@ -27,7 +27,7 @@ Unicode example to parse "Hello, World!" in Greek. <p>
<li><a href="chemicalFormulas.py">chemicalFormulas.py</a><br>
-Simple example to demonstrate the use of ParseResults returned from parseString().
+Simple example to demonstrate the use of ParseResults returned from parseString().
Parses a chemical formula (such as "H2O" or "C6H5OH"), and walks the returned list of tokens to calculate the molecular weight.
</li>
<p>
@@ -124,7 +124,7 @@ Parser for CORBA IDL files. </li>
<p>
-<li><a href="mozillaCalendarParser.py">mozillaCalendarParser.py</a>
+<li><a href="mozillaCalendarParser.py">mozillaCalendarParser.py</a>
<i>~ submission by Petri Savolainen</i><br>
Parser for Mozilla calendar (*.ics) files.
</li>
@@ -167,19 +167,19 @@ example configuration file. <p>
<li><a href="romanNumerals.py">romanNumerals.py</a><br>
-A Roman numeral generator and parser example, showing the power of parse actions
+A Roman numeral generator and parser example, showing the power of parse actions
to compile Roman numerals into their integer values.
</li>
<p>
<li><a href="removeLineBreaks.py">removeLineBreaks.py</a><br>
A string transformer that converts text files with hard line-breaks into one with line breaks
-only between paragraphs. Useful when converting downloads from
-<a href="http://www.gutenberg.org">Project Gutenberg</a> to import to word processing apps
+only between paragraphs. Useful when converting downloads from
+<a href="http://www.gutenberg.org">Project Gutenberg</a> to import to word processing apps
that can reformat paragraphs once hard line-breaks are removed, or for loading into your Palm Pilot for portable perusal.
<p>
-See <a href="Successful Methods of Public Speaking.txt">Successful Methods of Public Speaking.txt</a> and
-<a href="Successful Methods of Public Speaking(2).txt">Successful Methods of Public Speaking(2).txt</a> for a sample
+See <a href="Successful Methods of Public Speaking.txt">Successful Methods of Public Speaking.txt</a> and
+<a href="Successful Methods of Public Speaking(2).txt">Successful Methods of Public Speaking(2).txt</a> for a sample
before and after (text file courtesy of Project Gutenberg).
</li>
<p>
@@ -190,13 +190,13 @@ An example program showing the utility of the listAllMatches option when specify <p>
<li><a href="linenoExample.py">linenoExample.py</a><br>
-An example program showing how to use the string location to extract line and column numbers, or the
+An example program showing how to use the string location to extract line and column numbers, or the
source line of text.
</li>
<p>
<li><a href="parseListString.py">parseListString.py</a><br>
-An example program showing a progression of steps, how to parse a string representation of a Python
+An example program showing a progression of steps, how to parse a string representation of a Python
list back into a true list.
</li>
<p>
@@ -208,7 +208,7 @@ returning a Python value of the original type. <p>
<li><a href="indentedGrammarExample.py">indentedGrammarExample.py</a><br>
-An example program showing how to parse a grammar using indentation for grouping,
+An example program showing how to parse a grammar using indentation for grouping,
such as is done in Python.
</li>
<p>
@@ -220,7 +220,7 @@ An example program showing how to use the new operatorPrecedence helper method t <p>
<li><a href="simpleBool.py">simpleBool.py</a><br>
-An example program showing how to use the new operatorPrecedence helper method to define a
+An example program showing how to use the new operatorPrecedence helper method to define a
boolean expression parser, with parse actions associated with each operator to "compile" the expression
into a data structure that will evaluate the expression's boolean value.
</li>
@@ -290,7 +290,7 @@ domain objects instead of just strings. <li><a href="datetimeParseActions.py">datetimeParseActions.py</a><br>
<b>New in version 1.5.7</b><br>
-Parse actions example showing a parse action returning a datetime object instead of
+Parse actions example showing a parse action returning a datetime object instead of
string tokens, and doing validation of the tokens, raising a ParseException if the
given YYYY/MM/DD string does not represent a valid date.
</li>
@@ -298,7 +298,7 @@ given YYYY/MM/DD string does not represent a valid date. <li><a href="position.py">position.py</a><br>
<b>New in version 1.5.7</b><br>
-Demonstration of a couple of different ways to capture the location a particular
+Demonstration of a couple of different ways to capture the location a particular
expression was found within the overall input string.
</li>
<p>
diff --git a/examples/LAparser.py b/examples/LAparser.py index ec75d6c..8ffe073 100644 --- a/examples/LAparser.py +++ b/examples/LAparser.py @@ -4,11 +4,11 @@ Based on: SimpleCalc.py example (author Paul McGuire) in pyparsing-1.3.3 Author: Mike Ellis
Copyright: Ellis & Grant, Inc. 2005
License: You may freely use, modify, and distribute this software.
-Warranty: THIS SOFTWARE HAS NO WARRANTY WHATSOEVER. USE AT YOUR OWN RISK.
+Warranty: THIS SOFTWARE HAS NO WARRANTY WHATSOEVER. USE AT YOUR OWN RISK.
Notes: Parses infix linear algebra (LA) notation for vectors, matrices, and scalars.
- Output is C code function calls. The parser can be run as an interactive
- interpreter or included as module to use for in-place substitution into C files
- containing LA equations.
+ Output is C code function calls. The parser can be run as an interactive
+ interpreter or included as module to use for in-place substitution into C files
+ containing LA equations.
Supported operations are:
OPERATION: INPUT OUTPUT
@@ -34,27 +34,27 @@ Notes: Parses infix linear algebra (LA) notation for vectors, matrices, and scal Matrix determinant: "a = M3_b^Det" "a=mDeterminant(b)"
The parser requires the expression to be an equation. Each non-scalar variable
- must be prefixed with a type tag, 'M3_' for 3x3 matrices and 'V3_' for 3-vectors.
- For proper compilation of the C code, the variables need to be declared without
+ must be prefixed with a type tag, 'M3_' for 3x3 matrices and 'V3_' for 3-vectors.
+ For proper compilation of the C code, the variables need to be declared without
the prefix as float[3] for vectors and float[3][3] for matrices. The operations do
not modify any variables on the right-hand side of the equation.
- Equations may include nested expressions within parentheses. The allowed binary
+ Equations may include nested expressions within parentheses. The allowed binary
operators are '+-*/^' for scalars, and '+-*^@' for vectors and matrices with the
meanings defined in the table above.
Specifying an improper combination of operands, e.g. adding a vector to a matrix,
is detected by the parser and results in a Python TypeError Exception. The usual cause
- of this is omitting one or more tag prefixes. The parser knows nothing about a
- a variable's C declaration and relies entirely on the type tags. Errors in C
+ of this is omitting one or more tag prefixes. The parser knows nothing about a
+ a variable's C declaration and relies entirely on the type tags. Errors in C
declarations are not caught until compile time.
-Usage: To process LA equations embedded in source files, import this module and
+Usage: To process LA equations embedded in source files, import this module and
pass input and output file objects to the fprocess() function. You can
can also invoke the parser from the command line, e.g. 'python LAparser.py',
to run a small test suite and enter an interactive loop where you can enter
LA equations and see the resulting C code.
-
+
"""
import re,os,sys
@@ -87,7 +87,7 @@ def _assignVar( str, loc, toks ): point = Literal('.')
e = CaselessLiteral('E')
plusorminus = Literal('+') | Literal('-')
-number = Word(nums)
+number = Word(nums)
integer = Combine( Optional(plusorminus) + number )
floatnumber = Combine( integer +
Optional( point + Optional(number) ) +
@@ -103,7 +103,7 @@ ident = Forward() ## a ParseException.
ident = Combine(Word(alphas + '-',alphanums + '_') + \
ZeroOrMore(lbracket + (Word(alphas + '-',alphanums + '_')|integer) + rbracket) \
- )
+ )
plus = Literal( "+" )
minus = Literal( "-" )
@@ -118,14 +118,14 @@ expop = Literal( "^" ) assignop = Literal( "=" )
expr = Forward()
-atom = ( ( e | floatnumber | integer | ident ).setParseAction(_pushFirst) |
+atom = ( ( e | floatnumber | integer | ident ).setParseAction(_pushFirst) |
( lpar + expr.suppress() + rpar )
)
factor = Forward()
factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( _pushFirst ) )
-
+
term = factor + ZeroOrMore( ( multop + factor ).setParseAction( _pushFirst ) )
-expr << term + ZeroOrMore( ( addop + term ).setParseAction( _pushFirst ) )
+expr << term + ZeroOrMore( ( addop + term ).setParseAction( _pushFirst ) )
equation = (ident + assignop).setParseAction(_assignVar) + expr + StringEnd()
# End of grammar definition
@@ -143,12 +143,12 @@ class UnaryUnsupportedError(Exception): pass def _isvec(ident):
if ident[0] == '-' and ident[1:vplen+1] == vprefix:
- raise UnaryUnsupportedError
+ raise UnaryUnsupportedError
else: return ident[0:vplen] == vprefix
-def _ismat(ident):
+def _ismat(ident):
if ident[0] == '-' and ident[1:mplen+1] == mprefix:
- raise UnaryUnsupportedError
+ raise UnaryUnsupportedError
else: return ident[0:mplen] == mprefix
def _isscalar(ident): return not (_isvec(ident) or _ismat(ident))
@@ -163,41 +163,41 @@ def _isscalar(ident): return not (_isvec(ident) or _ismat(ident)) ## nested function calls, e.g. "V3_a + V3_b*5" yields "V3_vAdd(a,vScale(b,5)". Note that prefixes are
## stripped from operands and function names within the argument list to the outer function and
## the appropriate prefix is placed on the outer function for removal later as the stack evaluation
-## recurses toward the final assignment statement.
+## recurses toward the final assignment statement.
-def _addfunc(a,b):
+def _addfunc(a,b):
if _isscalar(a) and _isscalar(b): return "(%s+%s)"%(a,b)
- if _isvec(a) and _isvec(b): return "%svAdd(%s,%s)"%(vprefix,a[vplen:],b[vplen:])
- if _ismat(a) and _ismat(b): return "%smAdd(%s,%s)"%(mprefix,a[mplen:],b[mplen:])
+ if _isvec(a) and _isvec(b): return "%svAdd(%s,%s)"%(vprefix,a[vplen:],b[vplen:])
+ if _ismat(a) and _ismat(b): return "%smAdd(%s,%s)"%(mprefix,a[mplen:],b[mplen:])
else: raise TypeError
-def _subfunc(a,b):
+def _subfunc(a,b):
if _isscalar(a) and _isscalar(b): return "(%s-%s)"%(a,b)
- if _isvec(a) and _isvec(b): return "%svSubtract(%s,%s)"%(vprefix,a[vplen:],b[vplen:])
- if _ismat(a) and _ismat(b): return "%smSubtract(%s,%s)"%(mprefix,a[mplen:],b[mplen:])
+ if _isvec(a) and _isvec(b): return "%svSubtract(%s,%s)"%(vprefix,a[vplen:],b[vplen:])
+ if _ismat(a) and _ismat(b): return "%smSubtract(%s,%s)"%(mprefix,a[mplen:],b[mplen:])
else: raise TypeError
-def _mulfunc(a,b):
+def _mulfunc(a,b):
if _isscalar(a) and _isscalar(b): return "%s*%s"%(a,b)
- if _isvec(a) and _isvec(b): return "vDot(%s,%s)"%(a[vplen:],b[vplen:])
- if _ismat(a) and _ismat(b): return "%smMultiply(%s,%s)"%(mprefix,a[mplen:],b[mplen:])
- if _ismat(a) and _isvec(b): return "%smvMultiply(%s,%s)"%(vprefix,a[mplen:],b[vplen:])
- if _ismat(a) and _isscalar(b): return "%smScale(%s,%s)"%(mprefix,a[mplen:],b)
- if _isvec(a) and _isscalar(b): return "%svScale(%s,%s)"%(vprefix,a[mplen:],b)
+ if _isvec(a) and _isvec(b): return "vDot(%s,%s)"%(a[vplen:],b[vplen:])
+ if _ismat(a) and _ismat(b): return "%smMultiply(%s,%s)"%(mprefix,a[mplen:],b[mplen:])
+ if _ismat(a) and _isvec(b): return "%smvMultiply(%s,%s)"%(vprefix,a[mplen:],b[vplen:])
+ if _ismat(a) and _isscalar(b): return "%smScale(%s,%s)"%(mprefix,a[mplen:],b)
+ if _isvec(a) and _isscalar(b): return "%svScale(%s,%s)"%(vprefix,a[mplen:],b)
else: raise TypeError
def _outermulfunc(a,b):
## The '@' operator is used for the vector outer product.
- if _isvec(a) and _isvec(b):
+ if _isvec(a) and _isvec(b):
return "%svOuterProduct(%s,%s)"%(mprefix,a[vplen:],b[vplen:])
else: raise TypeError
def _divfunc(a,b):
- ## The '/' operator is used only for scalar division
+ ## The '/' operator is used only for scalar division
if _isscalar(a) and _isscalar(b): return "%s/%s"%(a,b)
else: raise TypeError
-def _expfunc(a,b):
+def _expfunc(a,b):
## The '^' operator is used for exponentiation on scalars and
## as a marker for unary operations on vectors and matrices.
if _isscalar(a) and _isscalar(b): return "pow(%s,%s)"%(str(a),str(b))
@@ -208,17 +208,17 @@ def _expfunc(a,b): if _isvec(a) and b=='Mag2': return "vMagnitude2(%s)"%(a[vplen:])
else: raise TypeError
-def _assignfunc(a,b):
+def _assignfunc(a,b):
## The '=' operator is used for assignment
if _isscalar(a) and _isscalar(b): return "%s=%s"%(a,b)
- if _isvec(a) and _isvec(b): return "vCopy(%s,%s)"%(a[vplen:],b[vplen:])
- if _ismat(a) and _ismat(b): return "mCopy(%s,%s)"%(a[mplen:],b[mplen:])
+ if _isvec(a) and _isvec(b): return "vCopy(%s,%s)"%(a[vplen:],b[vplen:])
+ if _ismat(a) and _ismat(b): return "mCopy(%s,%s)"%(a[mplen:],b[mplen:])
else: raise TypeError
## End of BIO func definitions
##----------------------------------------------------------------------------
-# Map operator symbols to corresponding BIO funcs
+# Map operator symbols to corresponding BIO funcs
opn = { "+" : ( _addfunc ),
"-" : ( _subfunc ),
"*" : ( _mulfunc ),
@@ -237,25 +237,25 @@ def _evaluateStack( s ): result = opn[op]( op1, op2 )
if debug_flag: print(result)
return result
- else:
+ else:
return op
##----------------------------------------------------------------------------
# The parse function that invokes all of the above.
def parse(input_string):
"""
- Accepts an input string containing an LA equation, e.g.,
+ Accepts an input string containing an LA equation, e.g.,
"M3_mymatrix = M3_anothermatrix^-1" returns C code function
calls that implement the expression.
"""
-
+
global exprStack
global targetvar
# Start with a blank exprStack and a blank targetvar
exprStack = []
targetvar=None
-
+
if input_string != '':
# try parsing the input string
try:
@@ -266,14 +266,14 @@ def parse(input_string): print(" "*(err.column-1) + "^", file=sys.stderr)
print(err, file=sys.stderr)
raise
-
+
# show result of parsing the input string
- if debug_flag:
+ if debug_flag:
print(input_string, "->", L)
print("exprStack=", exprStack)
-
+
# Evaluate the stack of parsed operands, emitting C code.
- try:
+ try:
result=_evaluateStack(exprStack)
except TypeError:
print("Unsupported operation on right side of '%s'.\nCheck for missing or incorrect tags on non-scalar operands."%input_string, file=sys.stderr)
@@ -281,8 +281,8 @@ def parse(input_string): except UnaryUnsupportedError:
print("Unary negation is not supported for vectors and matrices: '%s'"%input_string, file=sys.stderr)
raise
-
- # Create final assignment and print it.
+
+ # Create final assignment and print it.
if debug_flag: print("var=",targetvar)
if targetvar != None:
try:
@@ -311,22 +311,22 @@ def fprocess(infilep,outfilep): Other text in the file is unaltered.
- The arguments are file objects (NOT file names) opened for reading and
+ The arguments are file objects (NOT file names) opened for reading and
writing, respectively.
"""
pattern = r'\[\[\s*(.*?)\s*\]\]'
eqn = re.compile(pattern,re.DOTALL)
s = infilep.read()
- def parser(mo):
+ def parser(mo):
ccode = parse(mo.group(1))
return "/* %s */\n%s;\nLAParserBufferReset();\n"%(mo.group(1),ccode)
content = eqn.sub(parser,s)
outfilep.write(content)
-
+
##-----------------------------------------------------------------------------------
def test():
- """
+ """
Tests the parsing of various supported expressions. Raises
an AssertError if the output is not what is expected. Prints the
input, expected output, and actual output for all tests.
@@ -357,9 +357,9 @@ def test(): ("Vector magnitude","a = V3_b^Mag","a=sqrt(vMagnitude2(b))"),
("Complicated expression", "myscalar = (M3_amatrix * V3_bvector)^Mag + 5*(-xyz[i] + 2.03^2)","myscalar=(sqrt(vMagnitude2(mvMultiply(amatrix,bvector)))+5*(-xyz[i]+pow(2.03,2)))"),
("Complicated Multiline", "myscalar = \n(M3_amatrix * V3_bvector)^Mag +\n 5*(xyz + 2.03^2)","myscalar=(sqrt(vMagnitude2(mvMultiply(amatrix,bvector)))+5*(xyz+pow(2.03,2)))")
-
+
]
-
+
for t in testcases:
name,input,expected = t
print(name)
@@ -369,13 +369,13 @@ def test(): print(" %s received"%result)
print("")
assert expected == result
-
+
##TODO: Write testcases with invalid expressions and test that the expected
## exceptions are raised.
print("Tests completed!")
##----------------------------------------------------------------------------
-## The following is executed only when this module is executed as
+## The following is executed only when this module is executed as
## command line script. It runs a small test suite (see above)
## and then enters an interactive loop where you
## can enter expressions and see the resulting C code as output.
@@ -386,7 +386,7 @@ if __name__ == '__main__': # input_string
input_string=''
-
+
# Display instructions on how to use the program interactively
interactiveusage = """
Entering interactive mode:
@@ -396,7 +396,7 @@ if __name__ == '__main__': """
print(interactiveusage)
input_string = input("> ")
-
+
while input_string != 'quit':
if input_string == "debug on":
debug_flag = True
@@ -406,12 +406,10 @@ if __name__ == '__main__': try:
print(parse(input_string))
except:
- pass
+ pass
# obtain new input string
input_string = input("> ")
-
+
# if user types 'quit' then say goodbye
print("Good bye!")
-
-
diff --git a/examples/Setup.ini b/examples/Setup.ini index 4574b1c..a08016c 100644 --- a/examples/Setup.ini +++ b/examples/Setup.ini @@ -21,7 +21,7 @@ RemString1=Set up has finished remove ESS device driver and cleaned your system. RemString2=ESS devices is removed completely.No need to reboot. If you want to reinstall, run the setup again with driver package.
stshowmsg1=Setup will clean the installed files and update registry.
stshowmsg2=Setup is updating system's registry ....
-stshowmsg3=Setup is starting
+stshowmsg3=Setup is starting
sysdriver=es56cvmp.sys
mdmzn=mdmm3com.inf
@@ -34,7 +34,7 @@ audiocat=allem3.cat audioinf=M3i
sysaudio=es198xdl.sys
audiovxd=es198x.vxd
-
+
[Languages]
Default=0x0009
count=30
diff --git a/examples/SimpleCalc.py b/examples/SimpleCalc.py index 0bf62e4..15a1817 100644 --- a/examples/SimpleCalc.py +++ b/examples/SimpleCalc.py @@ -1,31 +1,31 @@ # SimpleCalc.py
#
-# Demonstration of the parsing module,
+# Demonstration of the parsing module,
# Sample usage
#
-# $ python SimpleCalc.py
+# $ python SimpleCalc.py
# Type in the string to be parse or 'quit' to exit the program
-# > g=67.89 + 7/5
+# > g=67.89 + 7/5
# 69.29
# > g
# 69.29
-# > h=(6*g+8.8)-g
+# > h=(6*g+8.8)-g
# 355.25
-# > h + 1
+# > h + 1
# 356.25
-# > 87.89 + 7/5
+# > 87.89 + 7/5
# 89.29
# > ans+10
# 99.29
# > quit
# Good bye!
#
-#
+#
# Uncomment the line below for readline support on interactive terminal
-# import readline
+# import readline
from pyparsing import ParseException, Word, alphas, alphanums
import math
@@ -64,11 +64,11 @@ pattern = assignment | arithExpr if __name__ == '__main__':
# input_string
input_string=''
-
+
# Display instructions on how to quit the program
print("Type in the string to be parsed or 'quit' to exit the program")
input_string = input("> ")
-
+
while input_string.strip().lower() != 'quit':
if input_string.strip().lower() == 'debug':
debug_flag=True
@@ -77,19 +77,19 @@ if __name__ == '__main__': # Reset to an empty exprStack
del exprStack[:]
-
+
if input_string != '':
# try parsing the input string
try:
L=pattern.parseString(input_string, parseAll=True)
except ParseException as err:
L=['Parse Failure', input_string, (str(err), err.line, err.column)]
-
+
# show result of parsing the input string
if debug_flag: print(input_string, "->", L)
if len(L)==0 or L[0] != 'Parse Failure':
if debug_flag: print("exprStack=", exprStack)
-
+
# calculate result , store a copy in ans , display the result to user
try:
result=evaluateStack(exprStack)
@@ -98,7 +98,7 @@ if __name__ == '__main__': else:
variables['ans']=result
print(result)
-
+
# Assign result to a variable if required
if L.varname:
variables[L.varname] = result
@@ -109,11 +109,9 @@ if __name__ == '__main__': print(err_line)
print(" "*(err_col-1) + "^")
print(err_str)
-
+
# obtain new input string
input_string = input("> ")
-
+
# if user type 'quit' then say goodbye
print("Good bye!")
-
-
diff --git a/examples/SingleForm.dfm b/examples/SingleForm.dfm index 7a52734..f036e5e 100644 --- a/examples/SingleForm.dfm +++ b/examples/SingleForm.dfm @@ -75,7 +75,7 @@ object Form1: TForm1 Connection.Params.Strings = (
'BlobSize=-1'
'CommitRetain=False'
-
+
'Database=C:\Program Files\Common Files\Borland Shared\Data\emplo' +
'yee.gdb'
'DriverName=Interbase'
diff --git a/examples/TAP.py b/examples/TAP.py index 139e47c..3c642e4 100644 --- a/examples/TAP.py +++ b/examples/TAP.py @@ -43,8 +43,8 @@ description = Regex("[^#\n]+") description.setParseAction(lambda t:t[0].lstrip('- '))
TODO,SKIP = map(CaselessLiteral,'TODO SKIP'.split())
-directive = Group(Suppress('#') + (TODO + restOfLine |
- FollowedBy(SKIP) +
+directive = Group(Suppress('#') + (TODO + restOfLine |
+ FollowedBy(SKIP) +
restOfLine.copy().setParseAction(lambda t:['SKIP',t[0]]) ))
commentLine = Suppress("#") + empty + restOfLine
@@ -52,11 +52,11 @@ commentLine = Suppress("#") + empty + restOfLine testLine = Group(
Optional(OneOrMore(commentLine + NL))("comments") +
testStatus("passed") +
- Optional(integer)("testNumber") +
- Optional(description)("description") +
+ Optional(integer)("testNumber") +
+ Optional(description)("description") +
Optional(directive)("directive")
)
-bailLine = Group(Literal("Bail out!")("BAIL") +
+bailLine = Group(Literal("Bail out!")("BAIL") +
empty + Optional(restOfLine)("reason"))
tapOutputParser = Optional(Group(plan)("plan") + NL) & \
@@ -89,7 +89,7 @@ class TAPSummary(object): expected = list(range(1, int(results.plan.ubound)+1))
else:
expected = list(range(1,len(results.tests)+1))
-
+
for i,res in enumerate(results.tests):
# test for bail out
if res.BAIL:
@@ -99,7 +99,7 @@ class TAPSummary(object): self.skippedTests += [ TAPTest.bailedTest(ii) for ii in expected[i:] ]
self.bailReason = res.reason
break
-
+
#~ print res.dump()
testnum = i+1
if res.testNumber != "":
@@ -109,16 +109,16 @@ class TAPSummary(object): res["testNumber"] = testnum
test = TAPTest(res)
- if test.passed:
+ if test.passed:
self.passedTests.append(test)
else:
self.failedTests.append(test)
if test.skipped: self.skippedTests.append(test)
if test.todo: self.todoTests.append(test)
if test.todo and test.passed: self.bonusTests.append(test)
-
+
self.passedSuite = not self.bail and (set(self.failedTests)-set(self.todoTests) == set())
-
+
def summary(self, showPassed=False, showAll=False):
testListStr = lambda tl : "[" + ",".join(str(t.num) for t in tl) + "]"
summaryText = []
diff --git a/examples/adventureEngine.py b/examples/adventureEngine.py index cdc618e..259c03e 100644 --- a/examples/adventureEngine.py +++ b/examples/adventureEngine.py @@ -10,10 +10,10 @@ import string def aOrAn( item ):
if item.desc[0] in "aeiou":
- return "an " + item.desc
+ return "an " + item.desc
else:
return "a " + item.desc
-
+
def enumerateItems(l):
if len(l) == 0: return "nothing"
out = []
@@ -31,33 +31,33 @@ def enumerateDoors(l): out.append("and")
out.append(l[-1])
return " ".join(out)
-
+
class Room(object):
def __init__(self, desc):
self.desc = desc
self.inv = []
self.gameOver = False
self.doors = [None,None,None,None]
-
+
def __getattr__(self,attr):
return \
- {
+ {
"n":self.doors[0],
"s":self.doors[1],
"e":self.doors[2],
"w":self.doors[3],
}[attr]
-
+
def enter(self,player):
if self.gameOver:
player.gameOver = True
-
+
def addItem(self, it):
self.inv.append(it)
-
+
def removeItem(self,it):
self.inv.remove(it)
-
+
def describe(self):
print(self.desc)
visibleItems = [ it for it in self.inv if it.isVisible ]
@@ -69,12 +69,12 @@ class Room(object): print("There {} {} here.".format(is_form, enumerateItems(visibleItems)))
else:
print("You see %s." % (enumerateItems(visibleItems)))
-
+
class Exit(Room):
def __init__(self):
super(Exit,self).__init__("")
-
+
def enter(self,player):
player.gameOver = True
@@ -94,10 +94,10 @@ class Item(object): self.usableConditionTest = None
self.cantTakeMessage = "You can't take that!"
Item.items[desc] = self
-
+
def __str__(self):
return self.desc
-
+
def breakItem(self):
if not self.isBroken:
print("<Crash!>")
@@ -109,7 +109,7 @@ class Item(object): return self.usableConditionTest( player, target )
else:
return False
-
+
def useItem(self, player, target):
if self.useAction:
self.useAction(player, self, target)
@@ -126,7 +126,7 @@ class OpenableItem(Item): self.contents = contents
else:
self.contents = []
-
+
def openItem(self, player):
if not self.isOpened:
self.isOpened = not self.isOpened
@@ -135,7 +135,7 @@ class OpenableItem(Item): player.room.addItem( item )
self.contents = []
self.desc = "open " + self.desc
-
+
def closeItem(self, player):
if self.isOpened:
self.isOpened = not self.isOpened
@@ -152,10 +152,10 @@ class Command(object): @staticmethod
def helpDescription():
return ""
-
+
def _doCommand(self, player):
pass
-
+
def __call__(self, player ):
print(self.verbProg.capitalize()+"...")
self._doCommand(player)
@@ -168,12 +168,12 @@ class MoveCommand(Command): @staticmethod
def helpDescription():
- return """MOVE or GO - go NORTH, SOUTH, EAST, or WEST
+ return """MOVE or GO - go NORTH, SOUTH, EAST, or WEST
(can abbreviate as 'GO N' and 'GO W', or even just 'E' and 'S')"""
-
+
def _doCommand(self, player):
rm = player.room
- nextRoom = rm.doors[
+ nextRoom = rm.doors[
{
"N":0,
"S":1,
@@ -195,7 +195,7 @@ class TakeCommand(Command): @staticmethod
def helpDescription():
return "TAKE or PICKUP or PICK UP - pick up an object (but some are deadly)"
-
+
def _doCommand(self, player):
rm = player.room
subj = Item.items[self.subject]
@@ -217,7 +217,7 @@ class DropCommand(Command): @staticmethod
def helpDescription():
return "DROP or LEAVE - drop an object (but fragile items may break)"
-
+
def _doCommand(self, player):
rm = player.room
subj = Item.items[self.subject]
@@ -234,7 +234,7 @@ class InventoryCommand(Command): @staticmethod
def helpDescription():
return "INVENTORY or INV or I - lists what items you have"
-
+
def _doCommand(self, player):
print("You have %s." % enumerateItems( player.inv ))
@@ -245,7 +245,7 @@ class LookCommand(Command): @staticmethod
def helpDescription():
return "LOOK or L - describes the current room and any objects in it"
-
+
def _doCommand(self, player):
player.room.describe()
@@ -256,7 +256,7 @@ class DoorsCommand(Command): @staticmethod
def helpDescription():
return "DOORS - display what doors are visible from this room"
-
+
def _doCommand(self, player):
rm = player.room
numDoors = sum([1 for r in rm.doors if r is not None])
@@ -267,7 +267,7 @@ class DoorsCommand(Command): reply = "There is a door to the "
else:
reply = "There are doors to the "
- doorNames = [ {0:"north", 1:"south", 2:"east", 3:"west"}[i]
+ doorNames = [ {0:"north", 1:"south", 2:"east", 3:"west"}[i]
for i,d in enumerate(rm.doors) if d is not None ]
#~ print doorNames
reply += enumerateDoors( doorNames )
@@ -286,7 +286,7 @@ class UseCommand(Command): @staticmethod
def helpDescription():
return "USE or U - use an object, optionally IN or ON another object"
-
+
def _doCommand(self, player):
rm = player.room
availItems = rm.inv + player.inv
@@ -306,7 +306,7 @@ class OpenCommand(Command): @staticmethod
def helpDescription():
return "OPEN or O - open an object"
-
+
def _doCommand(self, player):
rm = player.room
availItems = rm.inv+player.inv
@@ -329,7 +329,7 @@ class CloseCommand(Command): @staticmethod
def helpDescription():
return "CLOSE or CL - close an object"
-
+
def _doCommand(self, player):
rm = player.room
availItems = rm.inv+player.inv
@@ -351,7 +351,7 @@ class QuitCommand(Command): @staticmethod
def helpDescription():
return "QUIT or Q - ends the game"
-
+
def _doCommand(self, player):
print("Ok....")
player.gameOver = True
@@ -363,7 +363,7 @@ class HelpCommand(Command): @staticmethod
def helpDescription():
return "HELP or H or ? - displays this help message"
-
+
def _doCommand(self, player):
print("Enter any of the following commands (not case sensitive):")
for cmd in [
@@ -388,28 +388,28 @@ class AppParseException(ParseException): class Parser(object):
def __init__(self):
self.bnf = self.makeBNF()
-
+
def makeBNF(self):
- invVerb = oneOf("INV INVENTORY I", caseless=True)
- dropVerb = oneOf("DROP LEAVE", caseless=True)
+ invVerb = oneOf("INV INVENTORY I", caseless=True)
+ dropVerb = oneOf("DROP LEAVE", caseless=True)
takeVerb = oneOf("TAKE PICKUP", caseless=True) | \
(CaselessLiteral("PICK") + CaselessLiteral("UP") )
moveVerb = oneOf("MOVE GO", caseless=True) | empty
- useVerb = oneOf("USE U", caseless=True)
+ useVerb = oneOf("USE U", caseless=True)
openVerb = oneOf("OPEN O", caseless=True)
closeVerb = oneOf("CLOSE CL", caseless=True)
- quitVerb = oneOf("QUIT Q", caseless=True)
- lookVerb = oneOf("LOOK L", caseless=True)
+ quitVerb = oneOf("QUIT Q", caseless=True)
+ lookVerb = oneOf("LOOK L", caseless=True)
doorsVerb = CaselessLiteral("DOORS")
helpVerb = oneOf("H HELP ?",caseless=True)
-
+
itemRef = OneOrMore(Word(alphas)).setParseAction( self.validateItemName )
nDir = oneOf("N NORTH",caseless=True).setParseAction(replaceWith("N"))
sDir = oneOf("S SOUTH",caseless=True).setParseAction(replaceWith("S"))
eDir = oneOf("E EAST",caseless=True).setParseAction(replaceWith("E"))
wDir = oneOf("W WEST",caseless=True).setParseAction(replaceWith("W"))
moveDirection = nDir | sDir | eDir | wDir
-
+
invCommand = invVerb
dropCommand = dropVerb + itemRef("item")
takeCommand = takeVerb + itemRef("item")
@@ -423,7 +423,7 @@ class Parser(object): lookCommand = lookVerb
doorsCommand = doorsVerb
helpCommand = helpVerb
-
+
# attach command classes to expressions
invCommand.setParseAction(InventoryCommand)
dropCommand.setParseAction(DropCommand)
@@ -438,18 +438,18 @@ class Parser(object): helpCommand.setParseAction(HelpCommand)
# define parser using all command expressions
- return ( invCommand |
+ return ( invCommand |
useCommand |
- openCommand |
- closeCommand |
- dropCommand |
- takeCommand |
- moveCommand |
- lookCommand |
- doorsCommand |
+ openCommand |
+ closeCommand |
+ dropCommand |
+ takeCommand |
+ moveCommand |
+ lookCommand |
+ doorsCommand |
helpCommand |
quitCommand )("command") + LineEnd()
-
+
def validateItemName(self,s,l,t):
iname = " ".join(t)
if iname not in Item.items:
@@ -468,13 +468,13 @@ class Parser(object): "Excuse me?",
"???",
"What?" ] ))
-
+
class Player(object):
def __init__(self, name):
self.name = name
self.gameOver = False
self.inv = []
-
+
def moveTo(self, rm):
self.room = rm
rm.enter(self)
@@ -484,33 +484,33 @@ class Player(object): print("Game over!")
else:
rm.describe()
-
+
def take(self,it):
if it.isDeadly:
print("Aaaagh!...., the %s killed me!" % it)
self.gameOver = True
else:
self.inv.append(it)
-
+
def drop(self,it):
self.inv.remove(it)
if it.isFragile:
it.breakItem()
-
+
def createRooms( rm ):
"""
create rooms, using multiline string showing map layout
string contains symbols for the following:
- A-Z, a-z indicate rooms, and rooms will be stored in a dictionary by
+ A-Z, a-z indicate rooms, and rooms will be stored in a dictionary by
reference letter
-, | symbols indicate connection between rooms
<, >, ^, . symbols indicate one-way connection between rooms
"""
# start with empty dictionary of rooms
ret = {}
-
- # look for room symbols, and initialize dictionary
+
+ # look for room symbols, and initialize dictionary
# - exit room is always marked 'Z'
for c in rm:
if c in string.ascii_letters:
@@ -529,9 +529,9 @@ def createRooms( rm ): s = None
e = None
w = None
-
+
# look in neighboring cells for connection symbols (must take
- # care to guard that neighboring cells exist before testing
+ # care to guard that neighboring cells exist before testing
# contents)
if col > 0 and line[col-1] in "<-":
other = line[col-2]
diff --git a/examples/antlr_grammar.py b/examples/antlr_grammar.py index 76c681c..7863a77 100644 --- a/examples/antlr_grammar.py +++ b/examples/antlr_grammar.py @@ -23,14 +23,14 @@ INT = Word(nums) ESC = Literal('\\') + (oneOf(list(r'nrtbf\">'+"'")) | ('u' + Word(hexnums, exact=4)) | Word(printables, exact=1))
LITERAL_CHAR = ESC | ~(Literal("'") | Literal('\\')) + Word(printables, exact=1)
CHAR_LITERAL = Suppress("'") + LITERAL_CHAR + Suppress("'")
-STRING_LITERAL = Suppress("'") + Combine(OneOrMore(LITERAL_CHAR)) + Suppress("'")
+STRING_LITERAL = Suppress("'") + Combine(OneOrMore(LITERAL_CHAR)) + Suppress("'")
DOUBLE_QUOTE_STRING_LITERAL = '"' + ZeroOrMore(LITERAL_CHAR) + '"'
DOUBLE_ANGLE_STRING_LITERAL = '<<' + ZeroOrMore(Word(printables, exact=1)) + '>>'
TOKEN_REF = Word(alphas.upper(), alphanums+'_')
RULE_REF = Word(alphas.lower(), alphanums+'_')
ACTION_ESC = (Suppress("\\") + Suppress("'")) | Suppress('\\"') | Suppress('\\') + (~(Literal("'") | Literal('"')) + Word(printables, exact=1))
ACTION_CHAR_LITERAL = Suppress("'") + (ACTION_ESC | ~(Literal('\\') | Literal("'")) + Word(printables, exact=1)) + Suppress("'")
-ACTION_STRING_LITERAL = Suppress('"') + ZeroOrMore(ACTION_ESC | ~(Literal('\\') | Literal('"')) + Word(printables, exact=1)) + Suppress('"')
+ACTION_STRING_LITERAL = Suppress('"') + ZeroOrMore(ACTION_ESC | ~(Literal('\\') | Literal('"')) + Word(printables, exact=1)) + Suppress('"')
SRC = Suppress('src') + ACTION_STRING_LITERAL("file") + INT("line")
id = TOKEN_REF | RULE_REF
SL_COMMENT = Suppress('//') + Suppress('$ANTLR') + SRC | ZeroOrMore(~EOL + Word(printables)) + EOL
@@ -91,7 +91,7 @@ rewrite = Optional(Literal('TODO REWRITE RULES TODO')) block << Suppress('(') + Optional(Optional(optionsSpec("opts")) + Suppress(':')) + Group(alternative('a1') + rewrite + Group(ZeroOrMore(Suppress('|') + alternative('a2') + rewrite))("alternatives"))("block") + Suppress(')')
altList = alternative('a1') + rewrite + Group(ZeroOrMore(Suppress('|') + alternative('a2') + rewrite))("alternatives")
exceptionHandler = Suppress('catch') + ARG_ACTION + ACTION
-finallyClause = Suppress('finally') + ACTION
+finallyClause = Suppress('finally') + ACTION
exceptionGroup = (OneOrMore(exceptionHandler) + Optional(finallyClause)) | finallyClause
ruleHeading = Optional(ML_COMMENT)("ruleComment") + Optional(modifier)("modifier") + id("ruleName") + Optional("!") + Optional(ARG_ACTION("arg")) + Optional(Suppress('returns') + ARG_ACTION("rt")) + Optional(throwsSpec) + Optional(optionsSpec) + Optional(ruleScopeSpec) + ZeroOrMore(ruleAction)
@@ -125,7 +125,7 @@ def __antlrAlternativeConverter(pyparsingRules, antlrAlternative): regex = r'['+str(element.atom.c1[0])+'-'+str(element.atom.c2[0]+']')
rule = Regex(regex)("anonymous_regex")
elif hasattr(element, 'block') and element.block != '':
- rule = __antlrAlternativesConverter(pyparsingRules, element.block)
+ rule = __antlrAlternativesConverter(pyparsingRules, element.block)
else:
ruleRef = element.atom
assert ruleRef in pyparsingRules
@@ -145,7 +145,7 @@ def __antlrAlternativeConverter(pyparsingRules, antlrAlternative): rule = Group(And(elementList))("anonymous_and")
else:
rule = elementList[0]
- assert rule != None
+ assert rule != None
return rule
def __antlrRuleConverter(pyparsingRules, antlrRule):
@@ -169,11 +169,11 @@ def antlrConverter(antlrGrammarTree): for antlrRuleName, antlrRule in list(antlrRules.items()):
pyparsingRule = __antlrRuleConverter(pyparsingRules, antlrRule)
assert pyparsingRule != None
- pyparsingRules[antlrRuleName] << pyparsingRule
+ pyparsingRules[antlrRuleName] << pyparsingRule
return pyparsingRules
if __name__ == "__main__":
-
+
text = """grammar SimpleCalc;
options {
@@ -209,7 +209,7 @@ NUMBER : (DIGIT)+ ; fragment DIGIT : '0'..'9' ;
"""
-
+
grammar().validate()
antlrGrammarTree = grammar().parseString(text)
print(antlrGrammarTree.asXML("antlrGrammarTree"))
diff --git a/examples/apicheck.py b/examples/apicheck.py index 7bca41a..cd35a9a 100644 --- a/examples/apicheck.py +++ b/examples/apicheck.py @@ -13,8 +13,8 @@ LBRACK,RBRACK,LBRACE,RBRACE = map(Suppress,"[]{}") ident = Word(alphas,alphanums+"_") | QuotedString("{",endQuoteChar="}")
arg = "$" + ident
-# define an API call with a specific number of arguments - using '-'
-# will ensure that after matching procname, an incorrect number of args will
+# define an API call with a specific number of arguments - using '-'
+# will ensure that after matching procname, an incorrect number of args will
# raise a ParseSyntaxException, which will interrupt the scanString
def apiProc(name, numargs):
return LBRACK + Keyword(name)("procname") - arg*numargs + RBRACK
@@ -55,4 +55,3 @@ while 1: api_scanner = apiRef.scanString(test)
except StopIteration:
break
-
diff --git a/examples/cLibHeader.py b/examples/cLibHeader.py index bb98521..6bb1c25 100644 --- a/examples/cLibHeader.py +++ b/examples/cLibHeader.py @@ -1,4 +1,4 @@ -#
+#
# cLibHeader.py
#
# A simple parser to extract API doc info from a C header file
@@ -12,7 +12,7 @@ testdata = """ int func1(float *vec, int len, double arg1);
int func2(float **arr, float *vec, int len, double arg1, double arg2);
"""
-
+
ident = Word(alphas, alphanums + "_")
vartype = Combine( oneOf("float double int char") + Optional(Word("*")), adjacent = False)
arglist = delimitedList(Group(vartype("type") + ident("name")))
diff --git a/examples/chemicalFormulas.py b/examples/chemicalFormulas.py index ce66afd..31d77de 100644 --- a/examples/chemicalFormulas.py +++ b/examples/chemicalFormulas.py @@ -13,7 +13,7 @@ atomicWeight = { "Cl" : 35.4527,
"C" : 12.0107
}
-
+
def test( bnf, strg, fn=None ):
try:
print(strg,"->", bnf.parseString( strg ), end=' ')
@@ -62,6 +62,3 @@ fn = lambda elemList : sum(atomicWeight[elem.symbol]*elem.qty for elem in elemLi test( formula, "H2O", fn )
test( formula, "C6H5OH", fn )
test( formula, "NaCl", fn )
-
-
-
diff --git a/examples/configParse.py b/examples/configParse.py index 769249c..db7b6c7 100644 --- a/examples/configParse.py +++ b/examples/configParse.py @@ -15,7 +15,7 @@ import pprint inibnf = None
def inifile_BNF():
global inibnf
-
+
if not inibnf:
# punctuation
@@ -23,24 +23,24 @@ def inifile_BNF(): rbrack = Literal("]").suppress()
equals = Literal("=").suppress()
semi = Literal(";")
-
+
comment = semi + Optional( restOfLine )
-
+
nonrbrack = "".join( [ c for c in printables if c != "]" ] ) + " \t"
nonequals = "".join( [ c for c in printables if c != "=" ] ) + " \t"
-
+
sectionDef = lbrack + Word( nonrbrack ) + rbrack
keyDef = ~lbrack + Word( nonequals ) + equals + empty + restOfLine
# strip any leading or trailing blanks from key
def stripKey(tokens):
tokens[0] = tokens[0].strip()
keyDef.setParseAction(stripKey)
-
+
# using Dict will allow retrieval of named data fields as attributes of the parsed results
inibnf = Dict( ZeroOrMore( Group( sectionDef + Dict( ZeroOrMore( Group( keyDef ) ) ) ) ) )
-
+
inibnf.ignore( comment )
-
+
return inibnf
@@ -59,14 +59,13 @@ def test( strng ): print(err.line)
print(" "*(err.column-1) + "^")
print(err)
-
+
iniFile.close()
print()
return tokens
-
+
if __name__ == "__main__":
ini = test("setup.ini")
- print("ini['Startup']['modemid'] =", ini['Startup']['modemid'])
+ print("ini['Startup']['modemid'] =", ini['Startup']['modemid'])
print("ini.Startup =", ini.Startup)
print("ini.Startup.modemid =", ini.Startup.modemid)
-
diff --git a/examples/cpp_enum_parser.py b/examples/cpp_enum_parser.py index cd8f525..ca2c04b 100644 --- a/examples/cpp_enum_parser.py +++ b/examples/cpp_enum_parser.py @@ -3,7 +3,7 @@ #
# Posted by Mark Tolonen on comp.lang.python in August, 2009,
# Used with permission.
-#
+#
# Parser that scans through C or C++ code for enum definitions, and
# generates corresponding Python constant definitions.
#
diff --git a/examples/datetimeParseActions.py b/examples/datetimeParseActions.py index e42d2c6..aa9e016 100644 --- a/examples/datetimeParseActions.py +++ b/examples/datetimeParseActions.py @@ -37,16 +37,16 @@ date_expr.setParseAction(convertToDatetime) date_expr.runTests("""\
- 2000/1/1
+ 2000/1/1
# invalid month
- 2000/13/1
+ 2000/13/1
# 1900 was not a leap year
- 1900/2/29
+ 1900/2/29
# but 2000 was
- 2000/2/29
+ 2000/2/29
""")
@@ -55,14 +55,14 @@ date_expr = pyparsing_common.iso8601_date.setParseAction(pyparsing_common.conver date_expr.ignore(pythonStyleComment)
date_expr.runTests("""\
- 2000-01-01
+ 2000-01-01
# invalid month
- 2000-13-01
+ 2000-13-01
# 1900 was not a leap year
- 1900-02-29
+ 1900-02-29
# but 2000 was
- 2000-02-29
- """)
\ No newline at end of file + 2000-02-29
+ """)
diff --git a/examples/deltaTime.py b/examples/deltaTime.py index e38da00..2fa8769 100644 --- a/examples/deltaTime.py +++ b/examples/deltaTime.py @@ -1,9 +1,9 @@ # deltaTime.py
#
-# Parser to convert a conversational time reference such as "in a minute" or
-# "noon tomorrow" and convert it to a Python datetime. The returned
+# Parser to convert a conversational time reference such as "in a minute" or
+# "noon tomorrow" and convert it to a Python datetime. The returned
# ParseResults object contains the results name "timeOffset" containing
-# the timedelta, and "calculatedTime" containing the computed time relative
+# the timedelta, and "calculatedTime" containing the computed time relative
# to datetime.now().
#
# Copyright 2010, by Paul McGuire
@@ -30,7 +30,7 @@ def convertToTimedelta(toks): if toks.dir:
td *= toks.dir
toks["timeOffset"] = td
-
+
def convertToDay(toks):
now = datetime.now()
if "wkdayRef" in toks:
@@ -50,7 +50,7 @@ def convertToDay(toks): "yesterday" : datetime(now.year, now.month, now.day)+timedelta(-1),
"tomorrow" : datetime(now.year, now.month, now.day)+timedelta(+1),
}[name]
-
+
def convertToAbsTime(toks):
now = datetime.now()
if "dayRef" in toks:
@@ -70,7 +70,7 @@ def convertToAbsTime(toks): if hhmmss.miltime:
hh,mm = hhmmss.miltime
ss = 0
- else:
+ else:
hh,mm,ss = (hhmmss.HH % 12), hhmmss.MM, hhmmss.SS
if not mm: mm = 0
if not ss: ss = 0
@@ -80,7 +80,7 @@ def convertToAbsTime(toks): else:
timeOfDay = timedelta(0, (now.hour*60+now.minute)*60+now.second, now.microsecond)
toks["absTime"] = day + timeOfDay
-
+
def calculateTime(toks):
if toks.absTime:
absTime = toks.absTime
@@ -89,7 +89,7 @@ def calculateTime(toks): if toks.timeOffset:
absTime += toks.timeOffset
toks["calculatedTime"] = absTime
-
+
# grammar definitions
CL = CaselessLiteral
today, tomorrow, yesterday, noon, midnight, now = map( CL,
@@ -100,7 +100,7 @@ week, day, hour, minute, second = map( plural, am = CL("am")
pm = CL("pm")
COLON = Suppress(':')
-
+
# are these actually operators?
in_ = CL("in").setParseAction(replaceWith(1))
from_ = CL("from").setParseAction(replaceWith(1))
@@ -123,7 +123,7 @@ def fill_timefields(t): int4.addParseAction(fill_timefields)
qty = integer | couple | a_qty
dayName = oneOf( list(calendar.day_name) )
-
+
dayOffset = (qty("qty") + (week | day)("timeunit"))
dayFwdBack = (from_ + now.suppress() | ago)("dir")
weekdayRef = (Optional(next_ | last_,1)("dir") + dayName("day"))
@@ -132,37 +132,37 @@ dayRef = Optional( (dayOffset + (before | after | from_)("dir") ).setParseAction weekdayRef("wkdayRef")).setParseAction(convertToDay)
todayRef = (dayOffset + dayFwdBack).setParseAction(convertToTimedelta) | \
(in_("dir") + qty("qty") + day("timeunit")).setParseAction(convertToTimedelta)
-
+
dayTimeSpec = dayRef | todayRef
dayTimeSpec.setParseAction(calculateTime)
-
+
relativeTimeUnit = (week | day | hour | minute | second)
-
+
timespec = Group(ungroup(int4) |
- integer("HH") +
- ungroup(Optional(COLON + integer,[0]))("MM") +
- ungroup(Optional(COLON + integer,[0]))("SS") +
+ integer("HH") +
+ ungroup(Optional(COLON + integer,[0]))("MM") +
+ ungroup(Optional(COLON + integer,[0]))("SS") +
(am | pm)("ampm")
)
-absTimeSpec = ((noon | midnight | now | timespec("timeparts"))("timeOfDay") +
+absTimeSpec = ((noon | midnight | now | timespec("timeparts"))("timeOfDay") +
Optional(on_) + Optional(dayRef)("dayRef") |
- dayRef("dayRef") + at_ +
+ dayRef("dayRef") + at_ +
(noon | midnight | now | timespec("timeparts"))("timeOfDay"))
absTimeSpec.setParseAction(convertToAbsTime,calculateTime)
-
+
relTimeSpec = qty("qty") + relativeTimeUnit("timeunit") + \
(from_ | before | after)("dir") + \
Optional(at_) + \
absTimeSpec("absTime") | \
qty("qty") + relativeTimeUnit("timeunit") + ago("dir") | \
- in_ + qty("qty") + relativeTimeUnit("timeunit")
+ in_ + qty("qty") + relativeTimeUnit("timeunit")
relTimeSpec.setParseAction(convertToTimedelta,calculateTime)
-
-nlTimeExpression = (absTimeSpec + Optional(dayTimeSpec) |
- dayTimeSpec + Optional(Optional(at_) + absTimeSpec) |
+
+nlTimeExpression = (absTimeSpec + Optional(dayTimeSpec) |
+ dayTimeSpec + Optional(Optional(at_) + absTimeSpec) |
relTimeSpec + Optional(absTimeSpec))
-
+
if __name__ == "__main__":
# test grammar
tests = """\
diff --git a/examples/dfmparse.py b/examples/dfmparse.py index cf83814..28a3a9b 100644 --- a/examples/dfmparse.py +++ b/examples/dfmparse.py @@ -101,11 +101,11 @@ hint_attribute_value_pair = hint_attribute + EQUALS + value layout_attribute_value_pair = layout_attribute + EQUALS + value
generic_attribute_value_pair = attribute + EQUALS + value
attribute_value_pair << Group(
- category_attribute_value_pair
- | event_attribute_value_pair
- | font_attribute_value_pair
- | hint_attribute_value_pair
- | layout_attribute_value_pair
+ category_attribute_value_pair
+ | event_attribute_value_pair
+ | font_attribute_value_pair
+ | hint_attribute_value_pair
+ | layout_attribute_value_pair
| generic_attribute_value_pair
)
@@ -176,4 +176,4 @@ def main(testfiles=None, action=printer): return retval
if __name__ == "__main__":
- main()
\ No newline at end of file + main()
diff --git a/examples/dhcpd_leases_parser.py b/examples/dhcpd_leases_parser.py index 145e6ea..a885051 100644 --- a/examples/dhcpd_leases_parser.py +++ b/examples/dhcpd_leases_parser.py @@ -1,9 +1,9 @@ -#
+#
# dhcpd_leases_parser.py
#
# Copyright 2008, Paul McGuire
#
-# Sample parser to parse a dhcpd.leases file to extract leases
+# Sample parser to parse a dhcpd.leases file to extract leases
# and lease attributes
#
# format ref: http://www.linuxmanpages.com/man5/dhcpd.leases.5.php
diff --git a/examples/dictExample.py b/examples/dictExample.py index 5085aed..043d18f 100644 --- a/examples/dictExample.py +++ b/examples/dictExample.py @@ -21,8 +21,8 @@ testData = """ # define grammar for datatable
heading = (Literal(
-"+-------+------+------+------+------+------+------+------+------+") +
-"| | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 |" +
+"+-------+------+------+------+------+------+------+------+------+") +
+"| | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 |" +
"+=======+======+======+======+======+======+======+======+======+").suppress()
vert = Literal("|").suppress()
number = Word(nums)
diff --git a/examples/dictExample2.py b/examples/dictExample2.py index cae463b..0f243d3 100644 --- a/examples/dictExample2.py +++ b/examples/dictExample2.py @@ -44,9 +44,9 @@ print("sum(data['min']) =", sum(data['min'])) print("data.max =", data.max)
print("sum(data.max) =", sum(data.max))
-# now print transpose of data table, using column labels read from table header and
+# now print transpose of data table, using column labels read from table header and
# values from data lists
-print()
+print()
print(" " * 5, end=' ')
for i in range(1,len(data)):
print("|%5s" % data[i][0], end=' ')
@@ -56,4 +56,4 @@ for i in range(len(data.columns)): print("%5s" % data.columns[i], end=' ')
for j in range(len(data) - 1):
print('|%5s' % data[j + 1][i + 1], end=' ')
- print()
+ print()
diff --git a/examples/ebnf.py b/examples/ebnf.py index 242aed4..f94c755 100644 --- a/examples/ebnf.py +++ b/examples/ebnf.py @@ -55,7 +55,7 @@ syntax.ignore(ebnfComment) def do_integer(str, loc, toks):
return int(toks[0])
-
+
def do_meta_identifier(str, loc, toks):
if toks[0] in symbol_table:
return symbol_table[toks[0]]
diff --git a/examples/ebnftest.py b/examples/ebnftest.py index 253404f..40772ee 100644 --- a/examples/ebnftest.py +++ b/examples/ebnftest.py @@ -1,5 +1,5 @@ #
-# ebnftest.py
+# ebnftest.py
#
# Test script for ebnf.py
#
@@ -24,11 +24,11 @@ syntactic_primary = optional_sequence | repeated_sequence | optional_sequence = '[', definitions_list, ']';
repeated_sequence = '{', definitions_list, '}';
grouped_sequence = '(', definitions_list, ')';
-(*
+(*
terminal_string = "'", character - "'", {character - "'"}, "'" |
'"', character - '"', {character - '"'}, '"';
meta_identifier = letter, {letter | digit};
-integer = digit, {digit};
+integer = digit, {digit};
*)
'''
diff --git a/examples/eval_arith.py b/examples/eval_arith.py index 9562253..133f6c2 100644 --- a/examples/eval_arith.py +++ b/examples/eval_arith.py @@ -38,7 +38,7 @@ def operatorOperands(tokenlist): yield (next(it), next(it))
except StopIteration:
break
-
+
class EvalPowerOp(object):
"Class to evaluate multiplication and division expressions"
def __init__(self, tokens):
@@ -48,7 +48,7 @@ class EvalPowerOp(object): for val in self.value[-3::-2]:
res = val.eval()**res
return res
-
+
class EvalMultOp(object):
"Class to evaluate multiplication and division expressions"
def __init__(self, tokens):
@@ -61,7 +61,7 @@ class EvalMultOp(object): if op == '/':
prod /= val.eval()
return prod
-
+
class EvalAddOp(object):
"Class to evaluate addition and subtraction expressions"
def __init__(self, tokens):
@@ -105,7 +105,7 @@ class EvalComparisonOp(object): else:
return True
return False
-
+
# define the parser
integer = Word(nums)
@@ -137,57 +137,57 @@ comp_expr = infixNotation(arith_expr, def main():
# sample expressions posted on comp.lang.python, asking for advice
# in safely evaluating them
- rules=[
- '( A - B ) = 0',
- '(A + B + C + D + E + F + G + H + I) = J',
- '(A + B + C + D + E + F + G + H) = I',
- '(A + B + C + D + E + F) = G',
- '(A + B + C + D + E) = (F + G + H + I + J)',
- '(A + B + C + D + E) = (F + G + H + I)',
- '(A + B + C + D + E) = F',
- '(A + B + C + D) = (E + F + G + H)',
- '(A + B + C) = (D + E + F)',
- '(A + B) = (C + D + E + F)',
- '(A + B) = (C + D)',
- '(A + B) = (C - D + E - F - G + H + I + J)',
- '(A + B) = C',
- '(A + B) = 0',
- '(A+B+C+D+E) = (F+G+H+I+J)',
- '(A+B+C+D) = (E+F+G+H)',
- '(A+B+C+D)=(E+F+G+H)',
- '(A+B+C)=(D+E+F)',
- '(A+B)=(C+D)',
- '(A+B)=C',
- '(A-B)=C',
- '(A/(B+C))',
- '(B/(C+D))',
- '(G + H) = I',
- '-0.99 LE ((A+B+C)-(D+E+F+G)) LE 0.99',
- '-0.99 LE (A-(B+C)) LE 0.99',
- '-1000.00 LE A LE 0.00',
- '-5000.00 LE A LE 0.00',
- 'A < B',
- 'A < 7000',
- 'A = -(B)',
- 'A = C',
- 'A = 0',
- 'A GT 0',
- 'A GT 0.00',
- 'A GT 7.00',
- 'A LE B',
- 'A LT -1000.00',
- 'A LT -5000',
- 'A LT 0',
- 'A=(B+C+D)',
- 'A=B',
- 'I = (G + H)',
- '0.00 LE A LE 4.00',
+ rules=[
+ '( A - B ) = 0',
+ '(A + B + C + D + E + F + G + H + I) = J',
+ '(A + B + C + D + E + F + G + H) = I',
+ '(A + B + C + D + E + F) = G',
+ '(A + B + C + D + E) = (F + G + H + I + J)',
+ '(A + B + C + D + E) = (F + G + H + I)',
+ '(A + B + C + D + E) = F',
+ '(A + B + C + D) = (E + F + G + H)',
+ '(A + B + C) = (D + E + F)',
+ '(A + B) = (C + D + E + F)',
+ '(A + B) = (C + D)',
+ '(A + B) = (C - D + E - F - G + H + I + J)',
+ '(A + B) = C',
+ '(A + B) = 0',
+ '(A+B+C+D+E) = (F+G+H+I+J)',
+ '(A+B+C+D) = (E+F+G+H)',
+ '(A+B+C+D)=(E+F+G+H)',
+ '(A+B+C)=(D+E+F)',
+ '(A+B)=(C+D)',
+ '(A+B)=C',
+ '(A-B)=C',
+ '(A/(B+C))',
+ '(B/(C+D))',
+ '(G + H) = I',
+ '-0.99 LE ((A+B+C)-(D+E+F+G)) LE 0.99',
+ '-0.99 LE (A-(B+C)) LE 0.99',
+ '-1000.00 LE A LE 0.00',
+ '-5000.00 LE A LE 0.00',
+ 'A < B',
+ 'A < 7000',
+ 'A = -(B)',
+ 'A = C',
+ 'A = 0',
+ 'A GT 0',
+ 'A GT 0.00',
+ 'A GT 7.00',
+ 'A LE B',
+ 'A LT -1000.00',
+ 'A LT -5000',
+ 'A LT 0',
+ 'A=(B+C+D)',
+ 'A=B',
+ 'I = (G + H)',
+ '0.00 LE A LE 4.00',
'4.00 LT A LE 7.00',
'0.00 LE A LE 4.00 LE E > D',
'2**2**(A+3)',
- ]
- vars_={'A': 0, 'B': 1.1, 'C': 2.2, 'D': 3.3, 'E': 4.4, 'F': 5.5, 'G':
- 6.6, 'H':7.7, 'I':8.8, 'J':9.9}
+ ]
+ vars_={'A': 0, 'B': 1.1, 'C': 2.2, 'D': 3.3, 'E': 4.4, 'F': 5.5, 'G':
+ 6.6, 'H':7.7, 'I':8.8, 'J':9.9}
# define tests from given rules
tests = []
@@ -216,12 +216,12 @@ def main(): failed += 1
else:
print('')
-
+
print('')
if failed:
print(failed, "tests FAILED")
else:
print("all tests PASSED")
-if __name__=='__main__':
+if __name__=='__main__':
main()
diff --git a/examples/excelExpr.py b/examples/excelExpr.py index 7ce8db2..913d65b 100644 --- a/examples/excelExpr.py +++ b/examples/excelExpr.py @@ -1,12 +1,12 @@ # excelExpr.py
#
# Copyright 2010, Paul McGuire
-#
+#
# A partial implementation of a parser of Excel formula expressions.
#
-from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
- alphanums, nums, Optional, Group, oneOf, Forward, Regex,
- infixNotation, opAssoc, dblQuotedString, delimitedList,
+from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
+ alphanums, nums, Optional, Group, oneOf, Forward, Regex,
+ infixNotation, opAssoc, dblQuotedString, delimitedList,
Combine, Literal, QuotedString, ParserElement, pyparsing_common)
ParserElement.enablePackrat()
@@ -15,10 +15,10 @@ EXCL, DOLLAR = map(Literal,"!$") sheetRef = Word(alphas, alphanums) | QuotedString("'",escQuote="''")
colRef = Optional(DOLLAR) + Word(alphas,max=2)
rowRef = Optional(DOLLAR) + Word(nums)
-cellRef = Combine(Group(Optional(sheetRef + EXCL)("sheet") + colRef("col") +
+cellRef = Combine(Group(Optional(sheetRef + EXCL)("sheet") + colRef("col") +
rowRef("row")))
-cellRange = (Group(cellRef("start") + COLON + cellRef("end"))("range")
+cellRange = (Group(cellRef("start") + COLON + cellRef("end"))("range")
| cellRef | Word(alphas,alphanums))
expr = Forward()
@@ -26,10 +26,10 @@ expr = Forward() COMPARISON_OP = oneOf("< = > >= <= != <>")
condExpr = expr + COMPARISON_OP + expr
-ifFunc = (CaselessKeyword("if") -
- LPAR +
- Group(condExpr)("condition") +
- COMMA + Group(expr)("if_true") +
+ifFunc = (CaselessKeyword("if") -
+ LPAR +
+ Group(condExpr)("condition") +
+ COMMA + Group(expr)("if_true") +
COMMA + Group(expr)("if_false") + RPAR)
statFunc = lambda name : Group(CaselessKeyword(name) + Group(LPAR + delimitedList(expr) + RPAR))
@@ -42,7 +42,7 @@ funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc multOp = oneOf("* /")
addOp = oneOf("+ -")
numericLiteral = pyparsing_common.number
-operand = numericLiteral | funcCall | cellRange | cellRef
+operand = numericLiteral | funcCall | cellRange | cellRef
arithExpr = infixNotation(operand,
[
(multOp, 2, opAssoc.LEFT),
@@ -66,4 +66,4 @@ expr << (arithExpr | textExpr) =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))
=if("T"&a2="TTime", "Ready", "Not ready")
-""")
\ No newline at end of file +""")
diff --git a/examples/fourFn.py b/examples/fourFn.py index f485f53..484aa45 100644 --- a/examples/fourFn.py +++ b/examples/fourFn.py @@ -21,7 +21,7 @@ def pushFirst( strg, loc, toks ): exprStack.append( toks[0] )
def pushUMinus( strg, loc, toks ):
for t in toks:
- if t == '-':
+ if t == '-':
exprStack.append( 'unary -' )
#~ exprStack.append( '-1' )
#~ exprStack.append( '*' )
@@ -48,27 +48,27 @@ def BNF(): # and CaselessKeyword only match whole words
e = CaselessKeyword( "E" )
pi = CaselessKeyword( "PI" )
- #~ fnumber = Combine( Word( "+-"+nums, nums ) +
+ #~ 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, alphanums+"_$")
-
+
plus, minus, mult, div = map(Literal, "+-*/")
lpar, rpar = map(Suppress, "()")
addop = plus | minus
multop = mult | div
expop = Literal( "^" )
-
+
expr = Forward()
- atom = ((0,None)*minus + ( pi | e | fnumber | ident + lpar + expr + rpar | ident ).setParseAction( pushFirst ) |
- Group( lpar + expr + rpar )).setParseAction(pushUMinus)
-
+ atom = ((0,None)*minus + ( pi | e | fnumber | ident + lpar + expr + rpar | ident ).setParseAction( pushFirst ) |
+ Group( lpar + expr + rpar )).setParseAction(pushUMinus)
+
# by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-righ
# that is, 2^3^2 = 2^(3^2), not (2^3)^2.
factor = Forward()
factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) )
-
+
term = factor + ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) )
expr << term + ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) )
bnf = expr
@@ -109,7 +109,7 @@ def evaluateStack( s ): return float( op )
if __name__ == "__main__":
-
+
def test( s, expVal ):
global exprStack
exprStack[:] = []
@@ -125,7 +125,7 @@ if __name__ == "__main__": print(s, "=", val, results, "=>", exprStack)
else:
print(s+"!!!", val, "!=", expVal, results, "=>", exprStack)
-
+
test( "9", 9 )
test( "-9", -9 )
test( "--9", 9 )
diff --git a/examples/gen_ctypes.py b/examples/gen_ctypes.py index e79798f..325aa28 100644 --- a/examples/gen_ctypes.py +++ b/examples/gen_ctypes.py @@ -43,7 +43,7 @@ typemap = { "Bool" : "c_bool",
"void" : "None",
}
-
+
LPAR,RPAR,LBRACE,RBRACE,COMMA,SEMI = map(Suppress,"(){},;")
ident = Word(alphas, alphanums + "_")
integer = Regex(r"[+-]?\d+")
@@ -52,19 +52,19 @@ hexinteger = Regex(r"0x[0-9a-fA-F]+") const = Suppress("const")
primitiveType = oneOf(t for t in typemap if not t.endswith("*"))
structType = Suppress("struct") + ident
-vartype = (Optional(const) +
- (primitiveType | structType | ident) +
+vartype = (Optional(const) +
+ (primitiveType | structType | ident) +
Optional(Word("*")("ptr")))
def normalizetype(t):
if isinstance(t, ParseResults):
return ' '.join(t)
#~ ret = ParseResults([' '.join(t)])
#~ return ret
-
+
vartype.setParseAction(normalizetype)
arg = Group(vartype("argtype") + Optional(ident("argname")))
-func_def = (vartype("fn_type") + ident("fn_name") +
+func_def = (vartype("fn_type") + ident("fn_name") +
LPAR + Optional(delimitedList(arg|"..."))("fn_args") + RPAR + SEMI)
def derivefields(t):
if t.fn_args and t.fn_args[-1] == "...":
@@ -74,7 +74,7 @@ func_def.setParseAction(derivefields) fn_typedef = "typedef" + func_def
var_typedef = "typedef" + primitiveType("primType") + ident("name") + SEMI
-enum_def = (Keyword("enum") + LBRACE +
+enum_def = (Keyword("enum") + LBRACE +
delimitedList(Group(ident("name") + '=' + (hexinteger|integer)("value")))("evalues")
+ Optional(COMMA)
+ RBRACE)
@@ -131,7 +131,7 @@ for fn,_,_ in (cStyleComment.suppress() | fn_typedef.suppress() | func_def).scan if arg != "...":
if arg.argtype not in typemap:
getUDType(arg.argtype)
- functions.append(fn)
+ functions.append(fn)
# scan input header text for enums
enum_def.ignore(cppStyleComment)
@@ -160,7 +160,7 @@ print() print("# functions")
for fn in functions:
prefix = "{}.{}".format(module, fn.fn_name)
-
+
print("{}.restype = {}".format(prefix, typeAsCtypes(fn.fn_type)))
if fn.varargs:
print("# warning - %s takes variable argument list" % prefix)
@@ -170,5 +170,3 @@ for fn in functions: print("{}.argtypes = ({},)".format(prefix, ','.join(typeAsCtypes(a.argtype) for a in fn.fn_args)))
else:
print("%s.argtypes = ()" % (prefix))
-
-
diff --git a/examples/getNTPserversNew.py b/examples/getNTPserversNew.py index 6995b29..6eb653b 100644 --- a/examples/getNTPserversNew.py +++ b/examples/getNTPserversNew.py @@ -19,8 +19,8 @@ integer = Word(nums) ipAddress = Combine( integer + "." + integer + "." + integer + "." + integer )
hostname = delimitedList(Word(alphas,alphanums+"-_"),".",combine=True)
tdStart,tdEnd = makeHTMLTags("td")
-timeServerPattern = (tdStart + hostname("hostname") + tdEnd +
- tdStart + ipAddress("ipAddr") + tdEnd +
+timeServerPattern = (tdStart + hostname("hostname") + tdEnd +
+ tdStart + ipAddress("ipAddr") + tdEnd +
tdStart + SkipTo(tdEnd)("loc") + tdEnd)
# get list of time servers
diff --git a/examples/greetingInGreek.py b/examples/greetingInGreek.py index 921ac04..8dccd81 100644 --- a/examples/greetingInGreek.py +++ b/examples/greetingInGreek.py @@ -1,4 +1,4 @@ -# vim:fileencoding=utf-8
+# vim:fileencoding=utf-8
#
# greetingInGreek.py
#
@@ -10,11 +10,10 @@ from pyparsing import Word, pyparsing_unicode # define grammar
alphas = pyparsing_unicode.Greek.alphas
-greet = Word(alphas) + ',' + Word(alphas) + '!'
+greet = Word(alphas) + ',' + Word(alphas) + '!'
# input string
hello = "Καλημέρα, κόσμε!"
# parse input string
print(greet.parseString(hello))
-
diff --git a/examples/greetingInKorean.py b/examples/greetingInKorean.py index 2e9d4a1..7f5a17e 100644 --- a/examples/greetingInKorean.py +++ b/examples/greetingInKorean.py @@ -1,4 +1,4 @@ -# vim:fileencoding=utf-8
+# vim:fileencoding=utf-8
#
# greetingInKorean.py
#
diff --git a/examples/holaMundo.py b/examples/holaMundo.py index 47ab6bb..93dd881 100644 --- a/examples/holaMundo.py +++ b/examples/holaMundo.py @@ -2,32 +2,32 @@ # escrito por Marco Alfonso, 2004 Noviembre
-# importamos el modulo
-from pyparsing import *
-saludo= Word(alphas) + ',' + Word(alphas) + '!'
-
-# Aqui decimos que la gramatica "saludo" DEBE contener
-# una palabra compuesta de caracteres alfanumericos
-# (Word(alphas)) mas una ',' mas otra palabra alfanumerica,
-# mas '!' y esos seian nuestros tokens
-tokens = saludo.parseString("Hola, Mundo !")
-
-# Ahora parseamos una cadena, "Hola, Mundo!",
-# el metodo parseString, nos devuelve una lista con los tokens
-# encontrados, en caso de no haber errores...
+# importamos el modulo
+from pyparsing import *
+saludo= Word(alphas) + ',' + Word(alphas) + '!'
+
+# Aqui decimos que la gramatica "saludo" DEBE contener
+# una palabra compuesta de caracteres alfanumericos
+# (Word(alphas)) mas una ',' mas otra palabra alfanumerica,
+# mas '!' y esos seian nuestros tokens
+tokens = saludo.parseString("Hola, Mundo !")
+
+# Ahora parseamos una cadena, "Hola, Mundo!",
+# el metodo parseString, nos devuelve una lista con los tokens
+# encontrados, en caso de no haber errores...
for i in range(len(tokens)):
print ("Token %d -> %s" % (i,tokens[i]))
-#imprimimos cada uno de los tokens Y listooo!!, he aquí a salida
+#imprimimos cada uno de los tokens Y listooo!!, he aquí a salida
# Token 0 -> Hola
# Token 1 -> ,
-# Token 2-> Mundo
-# Token 3 -> !
-
-# Por supuesto, se pueden "reutilizar" gramáticas, por ejemplo:
-numimag = Word(nums) + 'i'
-numreal = Word(nums)
-numcomplex = numreal + '+' + numimag
+# Token 2-> Mundo
+# Token 3 -> !
+
+# Por supuesto, se pueden "reutilizar" gramáticas, por ejemplo:
+numimag = Word(nums) + 'i'
+numreal = Word(nums)
+numcomplex = numreal + '+' + numimag
print (numcomplex.parseString("3+5i"))
# Cambiar a complejo numero durante parsear:
@@ -35,4 +35,3 @@ numcomplex.setParseAction(lambda t: complex(''.join(t).replace('i','j'))) print (numcomplex.parseString("3+5i"))
# Excelente!!, bueno, los dejo, me voy a seguir tirando código...
-
diff --git a/examples/htmlStripper.py b/examples/htmlStripper.py index 1d7a0f0..6fc4aef 100644 --- a/examples/htmlStripper.py +++ b/examples/htmlStripper.py @@ -1,14 +1,14 @@ #
# htmlStripper.py
#
-# Sample code for stripping HTML markup tags and scripts from
+# Sample code for stripping HTML markup tags and scripts from
# HTML source files.
#
# Copyright (c) 2006, 2016, Paul McGuire
#
from contextlib import closing
import urllib.request, urllib.parse, urllib.error
-from pyparsing import (makeHTMLTags, SkipTo, commonHTMLEntity, replaceHTMLEntity,
+from pyparsing import (makeHTMLTags, SkipTo, commonHTMLEntity, replaceHTMLEntity,
htmlComment, anyOpenTag, anyCloseTag, LineEnd, OneOrMore, replaceWith)
scriptOpen,scriptClose = makeHTMLTags("script")
@@ -21,7 +21,7 @@ with closing(urllib.request.urlopen( targetURL )) as targetPage: targetHTML = targetPage.read().decode("UTF-8")
# first pass, strip out tags and translate entities
-firstPass = (htmlComment | scriptBody | commonHTMLEntity |
+firstPass = (htmlComment | scriptBody | commonHTMLEntity |
anyOpenTag | anyCloseTag ).suppress().transformString(targetHTML)
# first pass leaves many blank lines, collapse these down
@@ -29,4 +29,4 @@ repeatedNewlines = LineEnd() + OneOrMore(LineEnd()) repeatedNewlines.setParseAction(replaceWith("\n\n"))
secondPass = repeatedNewlines.transformString(firstPass)
-print(secondPass)
\ No newline at end of file +print(secondPass)
diff --git a/examples/httpServerLogParser.py b/examples/httpServerLogParser.py index a147a05..261cea3 100644 --- a/examples/httpServerLogParser.py +++ b/examples/httpServerLogParser.py @@ -5,11 +5,11 @@ """
Parser for HTTP server log output, of the form:
-195.146.134.15 - - [20/Jan/2003:08:55:36 -0800]
-"GET /path/to/page.html HTTP/1.0" 200 4649 "http://www.somedomain.com/020602/page.html"
+195.146.134.15 - - [20/Jan/2003:08:55:36 -0800]
+"GET /path/to/page.html HTTP/1.0" 200 4649 "http://www.somedomain.com/020602/page.html"
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
-127.0.0.1 - u.surname@domain.com [12/Sep/2006:14:13:53 +0300]
-"GET /skins/monobook/external.png HTTP/1.0" 304 - "http://wiki.mysite.com/skins/monobook/main.css"
+127.0.0.1 - u.surname@domain.com [12/Sep/2006:14:13:53 +0300]
+"GET /skins/monobook/external.png HTTP/1.0" 304 - "http://wiki.mysite.com/skins/monobook/main.css"
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6"
You can then break it up as follows:
@@ -32,30 +32,30 @@ def getCmdFields( s, l, t ): logLineBNF = None
def getLogLineBNF():
global logLineBNF
-
+
if logLineBNF is None:
integer = Word( nums )
ipAddress = delimitedList( integer, ".", combine=True )
-
+
timeZoneOffset = Word("+-",nums)
month = Word(string.uppercase, string.lowercase, exact=3)
- serverDateTime = Group( Suppress("[") +
+ serverDateTime = Group( Suppress("[") +
Combine( integer + "/" + month + "/" + integer +
":" + integer + ":" + integer + ":" + integer ) +
- timeZoneOffset +
+ timeZoneOffset +
Suppress("]") )
-
- logLineBNF = ( ipAddress.setResultsName("ipAddr") +
+
+ logLineBNF = ( ipAddress.setResultsName("ipAddr") +
Suppress("-") +
("-" | Word( alphas+nums+"@._" )).setResultsName("auth") +
- serverDateTime.setResultsName("timestamp") +
+ serverDateTime.setResultsName("timestamp") +
dblQuotedString.setResultsName("cmd").setParseAction(getCmdFields) +
- (integer | "-").setResultsName("statusCode") +
- (integer | "-").setResultsName("numBytesSent") +
+ (integer | "-").setResultsName("statusCode") +
+ (integer | "-").setResultsName("numBytesSent") +
dblQuotedString.setResultsName("referrer").setParseAction(removeQuotes) +
dblQuotedString.setResultsName("clientSfw").setParseAction(removeQuotes) )
return logLineBNF
-
+
testdata = """
195.146.134.15 - - [20/Jan/2003:08:55:36 -0800] "GET /path/to/page.html HTTP/1.0" 200 4649 "http://www.somedomain.com/020602/page.html" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
111.111.111.11 - - [16/Feb/2004:04:09:49 -0800] "GET /ads/redirectads/336x280redirect.htm HTTP/1.1" 304 - "http://www.foobarp.org/theme_detail.php?type=vs&cat=0&mid=27512" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)"
diff --git a/examples/idlParse.py b/examples/idlParse.py index b94bac4..37cb363 100644 --- a/examples/idlParse.py +++ b/examples/idlParse.py @@ -15,30 +15,30 @@ import pprint bnf = None
def CORBA_IDL_BNF():
global bnf
-
+
if not bnf:
# punctuation
(colon,lbrace,rbrace,lbrack,rbrack,lparen,rparen,
equals,comma,dot,slash,bslash,star,semi,langle,rangle) = map(Literal, r":{}[]()=,./\*;<>")
-
+
# keywords
- (any_, attribute_, boolean_, case_, char_, const_, context_, default_, double_, enum_, exception_,
- FALSE_, fixed_, float_, inout_, interface_, in_, long_, module_, Object_, octet_, oneway_, out_, raises_,
- readonly_, sequence_, short_, string_, struct_, switch_, TRUE_, typedef_, unsigned_, union_, void_,
- wchar_, wstring_) = map(Keyword, """any attribute boolean case char const context
- default double enum exception FALSE fixed float inout interface in long module
+ (any_, attribute_, boolean_, case_, char_, const_, context_, default_, double_, enum_, exception_,
+ FALSE_, fixed_, float_, inout_, interface_, in_, long_, module_, Object_, octet_, oneway_, out_, raises_,
+ readonly_, sequence_, short_, string_, struct_, switch_, TRUE_, typedef_, unsigned_, union_, void_,
+ wchar_, wstring_) = map(Keyword, """any attribute boolean case char const context
+ default double enum exception FALSE fixed float inout interface in long module
Object octet oneway out raises readonly sequence short string struct switch
TRUE typedef unsigned union void wchar wstring""".split())
-
+
identifier = Word( alphas, alphanums + "_" ).setName("identifier")
-
+
real = Regex(r"[+-]?\d+\.\d*([Ee][+-]?\d+)?").setName("real")
integer = Regex(r"0x[0-9a-fA-F]+|[+-]?\d+").setName("int")
udTypeName = delimitedList( identifier, "::", combine=True ).setName("udType")
- typeName = ( any_ | boolean_ | char_ | double_ | fixed_ |
- float_ | long_ | octet_ | short_ | string_ |
+ typeName = ( any_ | boolean_ | char_ | double_ | fixed_ |
+ float_ | long_ | octet_ | short_ | string_ |
wchar_ | wstring_ | udTypeName ).setName("type")
sequenceDef = Forward().setName("seq")
sequenceDef << Group( sequence_ + langle + ( sequenceDef | typeName ) + rangle )
@@ -60,11 +60,11 @@ def CORBA_IDL_BNF(): moduleDef << module_ + identifier + lbrace + ZeroOrMore( moduleItem ) + rbrace + semi
bnf = ( moduleDef | OneOrMore( moduleItem ) )
-
+
singleLineComment = "//" + restOfLine
bnf.ignore( singleLineComment )
bnf.ignore( cStyleComment )
-
+
return bnf
testnum = 1
@@ -84,7 +84,7 @@ def test( strng ): print(" "*(err.column-1) + "^")
print(err)
print()
-
+
if __name__ == "__main__":
test(
"""
@@ -94,7 +94,7 @@ if __name__ == "__main__": typedef string[10] tenStrings;
typedef sequence<string> stringSeq;
typedef sequence< sequence<string> > stringSeqSeq;
-
+
interface QoSAdmin {
stringSeq method1( in string arg1, inout long arg2 );
stringSeqSeq method2( in string arg1, inout long arg2, inout long arg3);
@@ -108,14 +108,14 @@ if __name__ == "__main__": * a block comment *
*/
typedef string[10] tenStrings;
- typedef
+ typedef
/** ** *** **** *
* a block comment *
*/
sequence<string> /*comment inside an And */ stringSeq;
/* */ /**/ /***/ /****/
typedef sequence< sequence<string> > stringSeqSeq;
-
+
interface QoSAdmin {
stringSeq method1( in string arg1, inout long arg2 );
stringSeqSeq method2( in string arg1, inout long arg2, inout long arg3);
@@ -135,7 +135,7 @@ if __name__ == "__main__": string msg;
sequence<string> dataStrings;
};
-
+
interface TestInterface
{
void method1( in string arg1, inout long arg2 );
@@ -144,16 +144,16 @@ if __name__ == "__main__": )
test(
"""
- module Test1
+ module Test1
{
exception TestException
{
string msg;
];
-
+
interface TestInterface
{
- void method1( in string arg1, inout long arg2 )
+ void method1( in string arg1, inout long arg2 )
raises ( TestException );
};
};
@@ -161,13 +161,13 @@ if __name__ == "__main__": )
test(
"""
- module Test1
+ module Test1
{
exception TestException
{
string msg;
};
-
+
};
"""
)
diff --git a/examples/indentedGrammarExample.py b/examples/indentedGrammarExample.py index 442e6a4..0133a9e 100644 --- a/examples/indentedGrammarExample.py +++ b/examples/indentedGrammarExample.py @@ -2,7 +2,7 @@ #
# Copyright (c) 2006,2016 Paul McGuire
#
-# A sample of a pyparsing grammar using indentation for
+# A sample of a pyparsing grammar using indentation for
# grouping (like Python does).
#
# Updated to use indentedBlock helper method.
@@ -51,4 +51,3 @@ module_body = OneOrMore(stmt) print(data)
parseTree = module_body.parseString(data)
parseTree.pprint()
-
diff --git a/examples/invRegex.py b/examples/invRegex.py index aea3b55..e935b3b 100644 --- a/examples/invRegex.py +++ b/examples/invRegex.py @@ -1,4 +1,4 @@ -#
+#
# invRegex.py
#
# Copyright 2008, Paul McGuire
@@ -13,7 +13,7 @@ #
__all__ = ["count","invert"]
-from pyparsing import (Literal, oneOf, printables, ParserElement, Combine,
+from pyparsing import (Literal, oneOf, printables, ParserElement, Combine,
SkipTo, infixNotation, ParseFatalException, Word, nums, opAssoc,
Suppress, ParseResults, srange)
@@ -76,7 +76,7 @@ class AlternativeEmitter(object): for s in e.makeGenerator()():
yield s
return altGen
-
+
class LiteralEmitter(object):
def __init__(self,lit):
self.lit = lit
@@ -91,7 +91,7 @@ class LiteralEmitter(object): def handleRange(toks):
return CharacterRangeEmitter(srange(toks[0]))
-
+
def handleRepetition(toks):
toks=toks[0]
if toks[1] in "*+":
@@ -111,7 +111,7 @@ def handleRepetition(toks): return GroupEmitter([toks[0]] * mincount + [opt])
else:
return [toks[0]] * mincount
-
+
def handleLiteral(toks):
lit = ""
for t in toks:
@@ -122,7 +122,7 @@ def handleLiteral(toks): lit += t[1]
else:
lit += t
- return LiteralEmitter(lit)
+ return LiteralEmitter(lit)
def handleMacro(toks):
macroChar = toks[0][1]
@@ -163,14 +163,14 @@ def parser(): repetition = (
( lbrace + Word(nums)("count") + rbrace ) |
( lbrace + Word(nums)("minCount")+","+ Word(nums)("maxCount") + rbrace ) |
- oneOf(list("*+?"))
+ oneOf(list("*+?"))
)
reRange.setParseAction(handleRange)
reLiteral.setParseAction(handleLiteral)
reMacro.setParseAction(handleMacro)
reDot.setParseAction(handleDot)
-
+
reTerm = ( reLiteral | reRange | reMacro | reDot | reNonCaptureGroup)
reExpr = infixNotation( reTerm,
[
@@ -180,7 +180,7 @@ def parser(): ]
)
_parser = reExpr
-
+
return _parser
def count(gen):
@@ -232,7 +232,7 @@ def main(): (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:
t = t.strip()
if not t: continue
diff --git a/examples/javascript_grammar.g b/examples/javascript_grammar.g index c30eac2..49fc238 100644 --- a/examples/javascript_grammar.g +++ b/examples/javascript_grammar.g @@ -15,25 +15,25 @@ options program
: LT!* sourceElements LT!* EOF!
;
-
+
sourceElements
: sourceElement (LT!* sourceElement)*
;
-
+
sourceElement
: functionDeclaration
| statement
;
-
+
// functions
functionDeclaration
: 'function' LT!* Identifier LT!* formalParameterList LT!* functionBody
;
-
+
functionExpression
: 'function' LT!* Identifier? LT!* formalParameterList LT!* functionBody
;
-
+
formalParameterList
: '(' (LT!* Identifier (LT!* ',' LT!* Identifier)*)? LT!* ')'
;
@@ -59,83 +59,83 @@ statement | throwStatement
| tryStatement
;
-
+
statementBlock
: '{' LT!* statementList? LT!* '}'
;
-
+
statementList
: statement (LT!* statement)*
;
-
+
variableStatement
: 'var' LT!* variableDeclarationList (LT | ';')!
;
-
+
variableDeclarationList
: variableDeclaration (LT!* ',' LT!* variableDeclaration)*
;
-
+
variableDeclarationListNoIn
: variableDeclarationNoIn (LT!* ',' LT!* variableDeclarationNoIn)*
;
-
+
variableDeclaration
: Identifier LT!* initialiser?
;
-
+
variableDeclarationNoIn
: Identifier LT!* initialiserNoIn?
;
-
+
initialiser
: '=' LT!* assignmentExpression
;
-
+
initialiserNoIn
: '=' LT!* assignmentExpressionNoIn
;
-
+
emptyStatement
: ';'
;
-
+
expressionStatement
: expression (LT | ';')!
;
-
+
ifStatement
: 'if' LT!* '(' LT!* expression LT!* ')' LT!* statement (LT!* 'else' LT!* statement)?
;
-
+
iterationStatement
: doWhileStatement
| whileStatement
| forStatement
| forInStatement
;
-
+
doWhileStatement
: 'do' LT!* statement LT!* 'while' LT!* '(' expression ')' (LT | ';')!
;
-
+
whileStatement
: 'while' LT!* '(' LT!* expression LT!* ')' LT!* statement
;
-
+
forStatement
: 'for' LT!* '(' (LT!* forStatementInitialiserPart)? LT!* ';' (LT!* expression)? LT!* ';' (LT!* expression)? LT!* ')' LT!* statement
;
-
+
forStatementInitialiserPart
: expressionNoIn
| 'var' LT!* variableDeclarationListNoIn
;
-
+
forInStatement
: 'for' LT!* '(' LT!* forInStatementInitialiserPart LT!* 'in' LT!* expression LT!* ')' LT!* statement
;
-
+
forInStatementInitialiserPart
: leftHandSideExpression
| 'var' LT!* variableDeclarationNoIn
@@ -152,7 +152,7 @@ breakStatement returnStatement
: 'return' expression? (LT | ';')!
;
-
+
withStatement
: 'with' LT!* '(' LT!* expression LT!* ')' LT!* statement
;
@@ -160,11 +160,11 @@ withStatement labelledStatement
: Identifier LT!* ':' LT!* statement
;
-
+
switchStatement
: 'switch' LT!* '(' LT!* expression LT!* ')' LT!* caseBlock
;
-
+
caseBlock
: '{' (LT!* caseClause)* (LT!* defaultClause (LT!* caseClause)*)? LT!* '}'
;
@@ -172,11 +172,11 @@ caseBlock caseClause
: 'case' LT!* expression LT!* ':' LT!* statementList?
;
-
+
defaultClause
: 'default' LT!* ':' LT!* statementList?
;
-
+
throwStatement
: 'throw' expression (LT | ';')!
;
@@ -184,11 +184,11 @@ throwStatement tryStatement
: 'try' LT!* statementBlock LT!* (finallyClause | catchClause (LT!* finallyClause)?)
;
-
+
catchClause
: 'catch' LT!* '(' LT!* Identifier LT!* ')' LT!* statementBlock
;
-
+
finallyClause
: 'finally' LT!* statementBlock
;
@@ -197,35 +197,35 @@ finallyClause expression
: assignmentExpression (LT!* ',' LT!* assignmentExpression)*
;
-
+
expressionNoIn
: assignmentExpressionNoIn (LT!* ',' LT!* assignmentExpressionNoIn)*
;
-
+
assignmentExpression
: conditionalExpression
| leftHandSideExpression LT!* assignmentOperator LT!* assignmentExpression
;
-
+
assignmentExpressionNoIn
: conditionalExpressionNoIn
| leftHandSideExpression LT!* assignmentOperator LT!* assignmentExpressionNoIn
;
-
+
leftHandSideExpression
: callExpression
| newExpression
;
-
+
newExpression
: memberExpression
| 'new' LT!* newExpression
;
-
+
memberExpression
: (primaryExpression | functionExpression | 'new' LT!* memberExpression LT!* arguments) (LT!* memberExpressionSuffix)*
;
-
+
memberExpressionSuffix
: indexSuffix
| propertyReferenceSuffix
@@ -234,7 +234,7 @@ memberExpressionSuffix callExpression
: memberExpression LT!* arguments (LT!* callExpressionSuffix)*
;
-
+
callExpressionSuffix
: arguments
| indexSuffix
@@ -244,15 +244,15 @@ callExpressionSuffix arguments
: '(' (LT!* assignmentExpression (LT!* ',' LT!* assignmentExpression)*)? LT!* ')'
;
-
+
indexSuffix
: '[' LT!* expression LT!* ']'
- ;
-
+ ;
+
propertyReferenceSuffix
: '.' LT!* Identifier
;
-
+
assignmentOperator
: '=' | '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '>>>=' | '&=' | '^=' | '|='
;
@@ -268,43 +268,43 @@ conditionalExpressionNoIn logicalORExpression
: logicalANDExpression (LT!* '||' LT!* logicalANDExpression)*
;
-
+
logicalORExpressionNoIn
: logicalANDExpressionNoIn (LT!* '||' LT!* logicalANDExpressionNoIn)*
;
-
+
logicalANDExpression
: bitwiseORExpression (LT!* '&&' LT!* bitwiseORExpression)*
;
-
+
logicalANDExpressionNoIn
: bitwiseORExpressionNoIn (LT!* '&&' LT!* bitwiseORExpressionNoIn)*
;
-
+
bitwiseORExpression
: bitwiseXORExpression (LT!* '|' LT!* bitwiseXORExpression)*
;
-
+
bitwiseORExpressionNoIn
: bitwiseXORExpressionNoIn (LT!* '|' LT!* bitwiseXORExpressionNoIn)*
;
-
+
bitwiseXORExpression
: bitwiseANDExpression (LT!* '^' LT!* bitwiseANDExpression)*
;
-
+
bitwiseXORExpressionNoIn
: bitwiseANDExpressionNoIn (LT!* '^' LT!* bitwiseANDExpressionNoIn)*
;
-
+
bitwiseANDExpression
: equalityExpression (LT!* '&' LT!* equalityExpression)*
;
-
+
bitwiseANDExpressionNoIn
: equalityExpressionNoIn (LT!* '&' LT!* equalityExpressionNoIn)*
;
-
+
equalityExpression
: relationalExpression (LT!* ('==' | '!=' | '===' | '!==') LT!* relationalExpression)*
;
@@ -312,7 +312,7 @@ equalityExpression equalityExpressionNoIn
: relationalExpressionNoIn (LT!* ('==' | '!=' | '===' | '!==') LT!* relationalExpressionNoIn)*
;
-
+
relationalExpression
: shiftExpression (LT!* ('<' | '>' | '<=' | '>=' | 'instanceof' | 'in') LT!* shiftExpression)*
;
@@ -337,7 +337,7 @@ unaryExpression : postfixExpression
| ('delete' | 'void' | 'typeof' | '++' | '--' | '+' | '-' | '~' | '!') unaryExpression
;
-
+
postfixExpression
: leftHandSideExpression ('++' | '--')?
;
@@ -350,17 +350,17 @@ primaryExpression | objectLiteral
| '(' LT!* expression LT!* ')'
;
-
+
// arrayLiteral definition.
arrayLiteral
: '[' LT!* assignmentExpression? (LT!* ',' (LT!* assignmentExpression)?)* LT!* ']'
;
-
+
// objectLiteral definition.
objectLiteral
: '{' LT!* propertyNameAndValue (LT!* ',' LT!* propertyNameAndValue)* LT!* '}'
;
-
+
propertyNameAndValue
: propertyName LT!* ':' LT!* assignmentExpression
;
@@ -379,20 +379,20 @@ literal | StringLiteral
| NumericLiteral
;
-
+
// lexer rules.
StringLiteral
: '"' DoubleStringCharacter* '"'
| '\'' SingleStringCharacter* '\''
;
-
+
fragment DoubleStringCharacter
- : ~('"' | '\\' | LT)
+ : ~('"' | '\\' | LT)
| '\\' EscapeSequence
;
fragment SingleStringCharacter
- : ~('\'' | '\\' | LT)
+ : ~('\'' | '\\' | LT)
| '\\' EscapeSequence
;
@@ -402,7 +402,7 @@ fragment EscapeSequence | HexEscapeSequence
| UnicodeEscapeSequence
;
-
+
fragment CharacterEscapeSequence
: SingleEscapeCharacter
| NonEscapeCharacter
@@ -422,33 +422,33 @@ fragment EscapeCharacter | 'x'
| 'u'
;
-
+
fragment HexEscapeSequence
: 'x' HexDigit HexDigit
;
-
+
fragment UnicodeEscapeSequence
: 'u' HexDigit HexDigit HexDigit HexDigit
;
-
+
NumericLiteral
: DecimalLiteral
| HexIntegerLiteral
;
-
+
fragment HexIntegerLiteral
: '0' ('x' | 'X') HexDigit+
;
-
+
fragment HexDigit
: DecimalDigit | ('a'..'f') | ('A'..'F')
;
-
+
fragment DecimalLiteral
: DecimalDigit+ '.' DecimalDigit* ExponentPart?
| '.'? DecimalDigit+ ExponentPart?
;
-
+
fragment DecimalDigit
: ('0'..'9')
;
@@ -460,21 +460,21 @@ fragment ExponentPart Identifier
: IdentifierStart IdentifierPart*
;
-
+
fragment IdentifierStart
: UnicodeLetter
| '$'
| '_'
| '\\' UnicodeEscapeSequence
;
-
+
fragment IdentifierPart
: (IdentifierStart) => IdentifierStart // Avoids ambiguity, as some IdentifierStart chars also match following alternatives.
| UnicodeDigit
| UnicodeConnectorPunctuation
;
-
-fragment UnicodeLetter // Any character in the Unicode categories "Uppercase letter (Lu)",
+
+fragment UnicodeLetter // Any character in the Unicode categories "Uppercase letter (Lu)",
: '\u0041'..'\u005A' // "Lowercase letter (Ll)", "Titlecase letter (Lt)",
| '\u0061'..'\u007A' // "Modifier letter (Lm)", "Other letter (Lo)", or "Letter number (Nl)".
| '\u00AA'
@@ -737,7 +737,7 @@ fragment UnicodeLetter // Any character in the Unicode categories "Uppercase le | '\uFFD2'..'\uFFD7'
| '\uFFDA'..'\uFFDC'
;
-
+
fragment UnicodeCombiningMark // Any character in the Unicode categories "Non-spacing mark (Mn)"
: '\u0300'..'\u034E' // or "Combining spacing mark (Mc)".
| '\u0360'..'\u0362'
@@ -745,7 +745,7 @@ fragment UnicodeCombiningMark // Any character in the Unicode categories "Non-sp | '\u0591'..'\u05A1'
| '\u05A3'..'\u05B9'
| '\u05BB'..'\u05BD'
- | '\u05BF'
+ | '\u05BF'
| '\u05C1'..'\u05C2'
| '\u05C4'
| '\u064B'..'\u0655'
@@ -863,7 +863,7 @@ fragment UnicodeDigit // Any character in the Unicode category "Decimal number | '\u1810'..'\u1819'
| '\uFF10'..'\uFF19'
;
-
+
fragment UnicodeConnectorPunctuation // Any character in the Unicode category "Connector punctuation (Pc)".
: '\u005F'
| '\u203F'..'\u2040'
@@ -873,7 +873,7 @@ fragment UnicodeConnectorPunctuation // Any character in the Unicode category "C | '\uFF3F'
| '\uFF65'
;
-
+
Comment
: '/*' (options {greedy=false;} : .)* '*/' {$channel=HIDDEN;}
;
diff --git a/examples/jsonParser.py b/examples/jsonParser.py index f080c6c..6319c36 100644 --- a/examples/jsonParser.py +++ b/examples/jsonParser.py @@ -11,19 +11,19 @@ # Updated 9 Aug 2016 - use more current pyparsing constructs/idioms
#
json_bnf = """
-object
- { members }
- {}
-members
- string : value
- members , string : value
-array
+object
+ { members }
+ {}
+members
+ string : value
+ members , string : value
+array
[ elements ]
- []
-elements
- value
- elements , value
-value
+ []
+elements
+ value
+ elements , value
+value
string
number
object
@@ -55,10 +55,10 @@ memberDef = Group(jsonString + COLON + jsonValue) jsonMembers = delimitedList(memberDef)
jsonObject << Dict(LBRACE + Optional(jsonMembers) + RBRACE)
-jsonComment = cppStyleComment
+jsonComment = cppStyleComment
jsonObject.ignore(jsonComment)
-
+
if __name__ == "__main__":
testdata = """
{
@@ -66,7 +66,7 @@ if __name__ == "__main__": "title": "example glossary",
"GlossDiv": {
"title": "S",
- "GlossList":
+ "GlossList":
{
"ID": "SGML",
"SortAs": "SGML",
@@ -103,5 +103,3 @@ if __name__ == "__main__": testPrint( results.glossary.GlossDiv.GlossList.Acronym )
testPrint( results.glossary.GlossDiv.GlossList.EvenPrimesGreaterThan2 )
testPrint( results.glossary.GlossDiv.GlossList.PrimesLessThan10 )
-
-
diff --git a/examples/linenoExample.py b/examples/linenoExample.py index 1186f48..0f84e10 100644 --- a/examples/linenoExample.py +++ b/examples/linenoExample.py @@ -22,8 +22,8 @@ def reportLongWords(st,locn,toks): print("The full line of text was:")
print("'%s'" % line(locn,st))
print((" "*col(locn,st))+" ^")
- print()
-
+ print()
+
wd = Word(alphas).setParseAction( reportLongWords )
OneOrMore(wd).parseString(data)
@@ -39,7 +39,7 @@ class Token(object): 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])
diff --git a/examples/listAllMatches.py b/examples/listAllMatches.py index 1b1bdd4..7301c84 100644 --- a/examples/listAllMatches.py +++ b/examples/listAllMatches.py @@ -49,4 +49,3 @@ print(sorted(set(results.cons))) print('')
print(results.others)
print(sorted(set(results.others)))
-
diff --git a/examples/lucene_grammar.py b/examples/lucene_grammar.py index 6e404d8..fc104e0 100644 --- a/examples/lucene_grammar.py +++ b/examples/lucene_grammar.py @@ -42,11 +42,11 @@ boost = (CARAT + number("boost")) string_expr = Group(string + proximity_modifier) | string
word_expr = Group(valid_word + fuzzy_modifier) | valid_word
-term << (Optional(field_name("field") + COLON) +
+term << (Optional(field_name("field") + COLON) +
(word_expr | string_expr | range_search | Group(LPAR + expression + RPAR)) +
Optional(boost))
term.setParseAction(lambda t:[t] if 'field' in t or 'boost' in t else None)
-
+
expression << infixNotation(term,
[
(required_modifier | prohibit_modifier, 1, opAssoc.RIGHT),
@@ -302,7 +302,7 @@ failtests = r""" XY\u005A
item:\ item:ABCD\
\
- a\ or b
+ a\ or b
a\:b\-c
a\:b\+c
a\:b\-c\*
@@ -315,5 +315,5 @@ failtests = r""" success1, _ = expression.runTests(tests)
success2, _ = expression.runTests(failtests, failureTests=True)
-
+
print(("FAIL", "OK")[success1 and success2])
diff --git a/examples/macroExpander.py b/examples/macroExpander.py index 327976c..c6b7034 100644 --- a/examples/macroExpander.py +++ b/examples/macroExpander.py @@ -1,6 +1,6 @@ # macroExpander.py
#
-# Example pyparsing program for performing macro expansion, similar to
+# Example pyparsing program for performing macro expansion, similar to
# the C pre-processor. This program is not as fully-featured, simply
# processing macros of the form:
# #def xxx yyyyy
@@ -14,11 +14,11 @@ #
from pyparsing import *
-# define the structure of a macro definition (the empty term is used
+# define the structure of a macro definition (the empty term is used
# to advance to the next non-whitespace character)
identifier = Word(alphas+"_",alphanums+"_")
macroDef = "#def" + identifier("macro") + empty + restOfLine("value")
-
+
# define a placeholder for defined macros - initially nothing
macroExpr = Forward()
macroExpr << NoMatch()
diff --git a/examples/matchPreviousDemo.py b/examples/matchPreviousDemo.py index f0812e9..34991f8 100644 --- a/examples/matchPreviousDemo.py +++ b/examples/matchPreviousDemo.py @@ -8,11 +8,11 @@ src = """ class a
...
end a;
-
+
class b
...
end b;
-
+
class c
...
end d;"""
@@ -20,7 +20,7 @@ end d;""" identifier = Word(alphas)
-classIdent = identifier("classname") # note that this also makes a copy of identifier
+classIdent = identifier("classname") # note that this also makes a copy of identifier
classHead = "class" + classIdent
classBody = "..."
classEnd = "end" + matchPreviousLiteral(classIdent) + ';'
@@ -30,4 +30,4 @@ classDefn = classHead + classBody + classEnd # classDefn = classHead + classBody - classEnd
for tokens in classDefn.searchString(src):
- print(tokens.classname)
\ No newline at end of file + print(tokens.classname)
diff --git a/examples/nested.py b/examples/nested.py index 24cf2f4..7a0f803 100644 --- a/examples/nested.py +++ b/examples/nested.py @@ -10,12 +10,12 @@ from pyparsing import * import pprint
data = """
-{
- { item1 "item with } in it" }
- {
- {item2a item2b }
- {item3}
- }
+{
+ { item1 "item with } in it" }
+ {
+ {item2a item2b }
+ {item3}
+ }
}
"""
@@ -27,4 +27,3 @@ print(( (nestedItems+stringEnd).parseString(data).asList() )) # use default delimiters of ()'s
mathExpr = nestedExpr()
print(( mathExpr.parseString( "((( ax + by)*C) *(Z | (E^F) & D))") ))
-
diff --git a/examples/numerics.py b/examples/numerics.py index 5ab99dd..0af3cae 100644 --- a/examples/numerics.py +++ b/examples/numerics.py @@ -9,41 +9,41 @@ # Format samples from https://docs.oracle.com/cd/E19455-01/806-0169/overview-9/index.html
#
tests = """\
-# Canadian (English and French)
-4 294 967 295,000
+# Canadian (English and French)
+4 294 967 295,000
-# Danish
-4 294 967 295,000
+# Danish
+4 294 967 295,000
-# Finnish
-4 294 967 295,000
+# Finnish
+4 294 967 295,000
-# French
-4 294 967 295,000
+# French
+4 294 967 295,000
-# German
-4 294 967 295,000
+# German
+4 294 967 295,000
-# Italian
-4.294.967.295,000
+# Italian
+4.294.967.295,000
-# Norwegian
-4.294.967.295,000
+# Norwegian
+4.294.967.295,000
-# Spanish
-4.294.967.295,000
+# Spanish
+4.294.967.295,000
-# Swedish
-4 294 967 295,000
+# Swedish
+4 294 967 295,000
-# GB-English
-4,294,967,295.000
+# GB-English
+4,294,967,295.000
-# US-English
-4,294,967,295.000
+# US-English
+4,294,967,295.000
-# Thai
-4,294,967,295.000
+# Thai
+4,294,967,295.000
"""
from pyparsing import Regex
diff --git a/examples/oc.py b/examples/oc.py index cf656ec..fdf7bcd 100644 --- a/examples/oc.py +++ b/examples/oc.py @@ -74,7 +74,7 @@ from pyparsing import * ParserElement.enablePackrat()
LPAR,RPAR,LBRACK,RBRACK,LBRACE,RBRACE,SEMI,COMMA = map(Suppress, "()[]{};,")
-INT, CHAR, WHILE, DO, IF, ELSE, RETURN = map(Keyword,
+INT, CHAR, WHILE, DO, IF, ELSE, RETURN = map(Keyword,
"int char while do if else return".split())
NAME = Word(alphas+"_", alphanums+"_")
@@ -86,7 +86,7 @@ TYPE = Group((INT | CHAR) + ZeroOrMore("*")) expr = Forward()
func_call = Group(NAME + LPAR + Group(Optional(delimitedList(expr))) + RPAR)
operand = func_call | NAME | integer | char | string_
-expr <<= (infixNotation(operand,
+expr <<= (infixNotation(operand,
[
(oneOf('! - *'), 1, opAssoc.RIGHT),
(oneOf('++ --'), 1, opAssoc.RIGHT),
@@ -95,8 +95,8 @@ expr <<= (infixNotation(operand, (oneOf('+ -'), 2, opAssoc.LEFT),
(oneOf('< == > <= >= !='), 2, opAssoc.LEFT),
(Regex(r'(?<!=)=(?!=)'), 2, opAssoc.LEFT),
- ]) +
- Optional( LBRACK + expr + RBRACK |
+ ]) +
+ Optional( LBRACK + expr + RBRACK |
LPAR + Group(Optional(delimitedList(expr))) + RPAR )
)
@@ -110,7 +110,7 @@ returnstmt = RETURN - expr + SEMI stmt << Group( ifstmt |
whilestmt |
dowhilestmt |
- returnstmt |
+ returnstmt |
expr + SEMI |
LBRACE + ZeroOrMore(stmt) + RBRACE |
SEMI)
diff --git a/examples/parsePythonValue.py b/examples/parsePythonValue.py index 53c61fc..351dad2 100644 --- a/examples/parsePythonValue.py +++ b/examples/parsePythonValue.py @@ -35,11 +35,11 @@ noneLiteral = Literal("None").setParseAction(replaceWith(None)) listItem = real|integer|quotedString|unicodeString|boolLiteral|noneLiteral| \
Group(listStr) | tupleStr | dictStr
-tupleStr << ( Suppress("(") + Optional(delimitedList(listItem)) +
+tupleStr << ( Suppress("(") + Optional(delimitedList(listItem)) +
Optional(Suppress(",")) + Suppress(")") )
tupleStr.setParseAction( cvtTuple )
-listStr << (lbrack + Optional(delimitedList(listItem) +
+listStr << (lbrack + Optional(delimitedList(listItem) +
Optional(Suppress(","))) + rbrack)
listStr.setParseAction(cvtList, lambda t: t[0])
diff --git a/examples/parseResultsSumExample.py b/examples/parseResultsSumExample.py index a18ba29..2c0f9fc 100644 --- a/examples/parseResultsSumExample.py +++ b/examples/parseResultsSumExample.py @@ -21,5 +21,3 @@ for test in (samplestr1,samplestr2,samplestr3,samplestr4,): print(person.id)
print(person.dump())
print()
-
-
diff --git a/examples/parseTabularData.py b/examples/parseTabularData.py index 3846310..5aa6f09 100644 --- a/examples/parseTabularData.py +++ b/examples/parseTabularData.py @@ -2,7 +2,7 @@ # parseTabularData.py
#
# Example of parsing data that is formatted in a tabular listing, with
-# potential for missing values. Uses new addCondition method on
+# potential for missing values. Uses new addCondition method on
# ParserElements.
#
# Copyright 2015, Paul McGuire
@@ -27,20 +27,20 @@ def mustMatchCols(startloc,endloc): def tableValue(expr, colstart, colend):
empty_cell_is_zero = False
if empty_cell_is_zero:
- return Optional(expr.copy().addCondition(mustMatchCols(colstart,colend),
- message="text not in expected columns"),
+ return Optional(expr.copy().addCondition(mustMatchCols(colstart,colend),
+ message="text not in expected columns"),
default=0)
else:
- return Optional(expr.copy().addCondition(mustMatchCols(colstart,colend),
+ return Optional(expr.copy().addCondition(mustMatchCols(colstart,colend),
message="text not in expected columns"))
# define the grammar for this simple table
colorname = Word(alphas)
integer = Word(nums).setParseAction(lambda t: int(t[0])).setName("integer")
-row = (colorname("name") +
- tableValue(integer, 11, 12)("S") +
- tableValue(integer, 15, 16)("M") +
+row = (colorname("name") +
+ tableValue(integer, 11, 12)("S") +
+ tableValue(integer, 15, 16)("M") +
tableValue(integer, 19, 20)("L"))
# parse the sample text - skip over the header and counter lines
diff --git a/examples/partial_gene_match.py b/examples/partial_gene_match.py index 8bf5f7c..e19cf8b 100644 --- a/examples/partial_gene_match.py +++ b/examples/partial_gene_match.py @@ -1,6 +1,6 @@ # parital_gene_match.py
#
-# Example showing how to create a customized pyparsing Token, in this case,
+# Example showing how to create a customized pyparsing Token, in this case,
# one that is very much like Literal, but which tolerates up to 'n' character
# mismatches
from pyparsing import *
@@ -12,77 +12,77 @@ datafile = urllib.request.urlopen("http://toxodb.org/common/downloads/release-6. fastasrc = datafile.read()
datafile.close()
-"""
-Sample header:
+"""
+Sample header:
>NC_001799-6-2978-2778 | organism=Toxoplasma_gondii_RH | location=NC_001799:2778-2978(-) | length=201
-"""
-integer = Word(nums).setParseAction(lambda t:int(t[0]))
-genebit = Group(">" + Word(alphanums.upper()+"-_") + "|" +
- Word(printables)("id") + SkipTo("length=", include=True) +
- integer("genelen") + LineEnd() +
- Combine(OneOrMore(Word("ACGTN")),adjacent=False)("gene"))
-
+"""
+integer = Word(nums).setParseAction(lambda t:int(t[0]))
+genebit = Group(">" + Word(alphanums.upper()+"-_") + "|" +
+ Word(printables)("id") + SkipTo("length=", include=True) +
+ integer("genelen") + LineEnd() +
+ Combine(OneOrMore(Word("ACGTN")),adjacent=False)("gene"))
+
# read gene data from .fasta file - takes just a few seconds
-genedata = OneOrMore(genebit).parseString(fastasrc)
+genedata = OneOrMore(genebit).parseString(fastasrc)
-class CloseMatch(Token):
+class CloseMatch(Token):
"""A special subclass of Token that does *close* matches. For each
close match of the given string, a tuple is returned giving the
found close match, and a list of mismatch positions."""
- def __init__(self, seq, maxMismatches=1):
- super(CloseMatch,self).__init__()
- self.name = seq
- self.sequence = seq
- self.maxMismatches = maxMismatches
- self.errmsg = "Expected " + self.sequence
- self.mayIndexError = False
- self.mayReturnEmpty = False
-
- def parseImpl( self, instring, loc, doActions=True ):
- start = loc
- instrlen = len(instring)
- maxloc = start + len(self.sequence)
-
- if maxloc <= instrlen:
- seq = self.sequence
- seqloc = 0
- mismatches = []
- throwException = False
- done = False
- while loc < maxloc and not done:
- if instring[loc] != seq[seqloc]:
- mismatches.append(seqloc)
- if len(mismatches) > self.maxMismatches:
- throwException = True
- done = True
- loc += 1
- seqloc += 1
- else:
- throwException = True
-
- if throwException:
- exc = self.myException
- exc.loc = loc
- exc.pstr = instring
- raise exc
-
- return loc, (instring[start:loc],mismatches)
+ def __init__(self, seq, maxMismatches=1):
+ super(CloseMatch,self).__init__()
+ self.name = seq
+ self.sequence = seq
+ self.maxMismatches = maxMismatches
+ self.errmsg = "Expected " + self.sequence
+ self.mayIndexError = False
+ self.mayReturnEmpty = False
+
+ def parseImpl( self, instring, loc, doActions=True ):
+ start = loc
+ instrlen = len(instring)
+ maxloc = start + len(self.sequence)
+
+ if maxloc <= instrlen:
+ seq = self.sequence
+ seqloc = 0
+ mismatches = []
+ throwException = False
+ done = False
+ while loc < maxloc and not done:
+ if instring[loc] != seq[seqloc]:
+ mismatches.append(seqloc)
+ if len(mismatches) > self.maxMismatches:
+ throwException = True
+ done = True
+ loc += 1
+ seqloc += 1
+ else:
+ throwException = True
+
+ if throwException:
+ exc = self.myException
+ exc.loc = loc
+ exc.pstr = instring
+ raise exc
+
+ return loc, (instring[start:loc],mismatches)
# using the genedata extracted above, look for close matches of a gene sequence
searchseq = CloseMatch("TTAAATCTAGAAGAT", 3)
-for g in genedata:
- print("%s (%d)" % (g.id, g.genelen))
- print("-"*24)
- for t,startLoc,endLoc in searchseq.scanString(g.gene, overlap=True):
- matched, mismatches = t[0]
- print("MATCH:", searchseq.sequence)
- print("FOUND:", matched)
- if mismatches:
- print(" ", ''.join(' ' if i not in mismatches else '*'
- for i,c in enumerate(searchseq.sequence)))
- else:
- print("<exact match>")
- print("at location", startLoc)
- print()
- print()
\ No newline at end of file +for g in genedata:
+ print("%s (%d)" % (g.id, g.genelen))
+ print("-"*24)
+ for t,startLoc,endLoc in searchseq.scanString(g.gene, overlap=True):
+ matched, mismatches = t[0]
+ print("MATCH:", searchseq.sequence)
+ print("FOUND:", matched)
+ if mismatches:
+ print(" ", ''.join(' ' if i not in mismatches else '*'
+ for i,c in enumerate(searchseq.sequence)))
+ else:
+ print("<exact match>")
+ print("at location", startLoc)
+ print()
+ print()
diff --git a/examples/position.py b/examples/position.py index 984c018..d88c14a 100644 --- a/examples/position.py +++ b/examples/position.py @@ -1,12 +1,12 @@ from pyparsing import *
-text = """Lorem ipsum dolor sit amet, consectetur adipisicing
-elit, sed do eiusmod tempor incididunt ut labore et dolore magna
-aliqua. Ut enim ad minim veniam, quis nostrud exercitation
-ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
-aute irure dolor in reprehenderit in voluptate velit esse cillum
-dolore eu fugiat nulla pariatur. Excepteur sint occaecat
-cupidatat non proident, sunt in culpa qui officia deserunt
+text = """Lorem ipsum dolor sit amet, consectetur adipisicing
+elit, sed do eiusmod tempor incididunt ut labore et dolore magna
+aliqua. Ut enim ad minim veniam, quis nostrud exercitation
+ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
+aute irure dolor in reprehenderit in voluptate velit esse cillum
+dolore eu fugiat nulla pariatur. Excepteur sint occaecat
+cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum"""
# find all words beginning with a vowel
@@ -51,5 +51,3 @@ for ivowelInfo in (initialConsWord | locateInitialVowels).searchString(text): if not ivowelInfo:
continue
print(ivowelInfo.locn, ':', ivowelInfo.word)
-
-
diff --git a/examples/protobuf_parser.py b/examples/protobuf_parser.py index 8f8b12d..9be2c7e 100644 --- a/examples/protobuf_parser.py +++ b/examples/protobuf_parser.py @@ -14,7 +14,7 @@ integer = Regex(r"[+-]?\d+") LBRACE,RBRACE,LBRACK,RBRACK,LPAR,RPAR,EQ,SEMI = map(Suppress,"{}[]()=;")
-kwds = """message required optional repeated enum extensions extends extend
+kwds = """message required optional repeated enum extensions extends extend
to package service rpc returns true false option import"""
for kw in kwds.split():
exec("{}_ = Keyword('{}')".format(kw.upper(), kw))
@@ -23,11 +23,11 @@ messageBody = Forward() messageDefn = MESSAGE_ - ident("messageId") + LBRACE + messageBody("body") + RBRACE
-typespec = oneOf("""double float int32 int64 uint32 uint64 sint32 sint64
+typespec = oneOf("""double float int32 int64 uint32 uint64 sint32 sint64
fixed32 fixed64 sfixed32 sfixed64 bool string bytes""") | ident
rvalue = integer | TRUE_ | FALSE_ | ident
fieldDirective = LBRACK + Group(ident + EQ + rvalue) + RBRACK
-fieldDefn = (( REQUIRED_ | OPTIONAL_ | REPEATED_ )("fieldQualifier") -
+fieldDefn = (( REQUIRED_ | OPTIONAL_ | REPEATED_ )("fieldQualifier") -
typespec("typespec") + ident("ident") + EQ + integer("fieldint") + ZeroOrMore(fieldDirective) + SEMI)
# enumDefn ::= 'enum' ident '{' { ident '=' integer ';' }* '}'
@@ -43,8 +43,8 @@ messageExtension = EXTEND_ - ident + LBRACE + messageBody + RBRACE messageBody << Group(ZeroOrMore( Group(fieldDefn | enumDefn | messageDefn | extensionsDefn | messageExtension) ))
# methodDefn ::= 'rpc' ident '(' [ ident ] ')' 'returns' '(' [ ident ] ')' ';'
-methodDefn = (RPC_ - ident("methodName") +
- LPAR + Optional(ident("methodParam")) + RPAR +
+methodDefn = (RPC_ - ident("methodName") +
+ LPAR + Optional(ident("methodParam")) + RPAR +
RETURNS_ + LPAR + Optional(ident("methodReturn")) + RPAR)
# serviceDefn ::= 'service' ident '{' methodDefn* '}'
@@ -66,10 +66,10 @@ parser = Optional(packageDirective) + ZeroOrMore(topLevelStatement) parser.ignore(comment)
-test1 = """message Person {
- required int32 id = 1;
- required string name = 2;
- optional string email = 3;
+test1 = """message Person {
+ required int32 id = 1;
+ required string name = 2;
+ optional string email = 3;
}"""
test2 = """package tutorial;
diff --git a/examples/pymicko.py b/examples/pymicko.py index 0db2938..e0fe205 100644 --- a/examples/pymicko.py +++ b/examples/pymicko.py @@ -62,7 +62,7 @@ DEBUG = 0 # (small subset of C made for compiler course at Faculty of Technical Sciences, Chair for Applied Computer Sciences, Novi Sad, Serbia)
# Patterns:
-
+
# letter
# -> "_" | "a" | "A" | "b" | "B" | "c" | "C" | "d" | "D" | "e" | "E" | "f"
# | "F" | "g" | "G" | "h" | "H" | "i" | "I" | "j" | "J" | "k" | "K" | "l"
@@ -72,56 +72,56 @@ DEBUG = 0 # digit
# -> "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
-
+
# identifier
# -> letter ( letter | digit )*
-
+
# int_constant
# -> digit +
-
+
# unsigned_constant
# -> digit + ( "u" | "U" )
-
+
# Productions:
-
+
# program
# -> variable_list function_list
# -> function_list
-
+
# variable_list
# -> variable ";"
# -> variable_list variable ";"
-
+
# variable
# -> type identifier
-
+
# type
# -> "int"
# -> "unsigned"
-
+
# function_list
# -> function
# -> function_list function
-
+
# function
# -> type identifier "(" parameters ")" body
-
+
# parameters
# -> <empty>
# -> parameter_list
-
+
# parameter_list
# -> variable
# -> parameter_list "," variable
-
+
# body
# -> "{" variable_list statement_list "}"
# -> "{" statement_list "}"
-
+
# statement_list
# -> <empty>
# -> statement_list statement
-
+
# statement
# -> assignement_statement
# -> function_call_statement
@@ -129,20 +129,20 @@ DEBUG = 0 # -> while_statement
# -> return_statement
# -> compound_statement
-
+
# assignement_statement
# -> identifier "=" num_exp ";"
-
+
# num_exp
# -> mul_exp
# -> num_exp "+" mul_exp
# -> num_exp "-" mul_exp
-
+
# mul_exp
# -> exp
# -> mul_exp "*" exp
# -> mul_exp "/" exp
-
+
# exp
# -> constant
# -> identifier
@@ -150,38 +150,38 @@ DEBUG = 0 # -> "(" num_exp ")"
# -> "+" exp
# -> "-" exp
-
+
# constant
# -> int_constant
# -> unsigned_constant
-
+
# function_call
# -> identifier "(" arguments ")"
-
+
# arguments
# -> <empty>
# -> argument_list
-
+
# argument_list
# -> num_exp
# -> argument_list "," num_exp
-
+
# function_call_statement
# -> function_call ";"
-
+
# if_statement
# -> "if" "(" log_exp ")" statement
# -> "if" "(" log_exp ")" statement "else" statement
# -> -> -> -> -> -> -> -> 2
-
+
# log_exp
# -> and_exp
# -> log_exp "||" and_exp
-
+
# and_exp
# -> rel_exp
# -> and_exp "&&" rel_exp
-
+
# rel_exp
# -> num_exp "<" num_exp
# -> num_exp ">" num_exp
@@ -189,16 +189,16 @@ DEBUG = 0 # -> num_exp ">=" num_exp
# -> num_exp "==" num_exp
# -> num_exp "!=" num_exp
-
+
# while_statement
# -> "while" "(" log_exp ")" statement
-
+
# return_statement
# -> "return" num_exp ";"
-
+
# compound_statement
# -> "{" statement_list "}"
-
+
# Comment: /* a comment */
##########################################################################################
@@ -280,13 +280,13 @@ class SemanticException(Exception): self.text = line(exshared.location, exshared.text)
else:
self.line = self.col = self.text = None
-
- def _get_message(self):
+
+ def _get_message(self):
return self._message
- def _set_message(self, message):
+ def _set_message(self, message):
self._message = message
message = property(_get_message, _set_message)
-
+
def __str__(self):
"""String representation of the semantic error"""
msg = "Error"
@@ -322,7 +322,7 @@ class SymbolTableEntry(object): """Sets attribute's name and value"""
self.attribute_name = name
self.attribute = value
-
+
def attribute_str(self):
"""Returns attribute string (used only for table display)"""
return "{}={}".format(self.attribute_name, self.attribute) if self.attribute != None else "None"
@@ -468,7 +468,7 @@ class SymbolTable(object): except Exception:
self.error()
return same
-
+
def same_type_as_argument(self, index, function_index, argument_number):
"""Returns True if index and function's argument are of the same type
index - index in symbol table
@@ -924,7 +924,7 @@ class MicroC(object): if print_location and (exshared.location != None):
msg += "\n%s" % wtext
print(msg)
-
+
def data_begin_action(self):
"""Inserts text at start of data segment"""
@@ -1311,7 +1311,7 @@ if 0: #main program
mc = MicroC()
output_file = "output.asm"
-
+
if len(argv) == 1:
input_file = stdin
elif len(argv) == 2:
@@ -1345,7 +1345,7 @@ if 0: ##########################################################################################
if __name__ == "__main__":
-
+
test_program_example = """
int a;
int b;
@@ -1384,4 +1384,4 @@ if __name__ == "__main__": mc = MicroC()
mc.parse_text(test_program_example)
- print(mc.codegen.code)
\ No newline at end of file + print(mc.codegen.code)
diff --git a/examples/pythonGrammarParser.py b/examples/pythonGrammarParser.py index 706f758..aed6bbe 100644 --- a/examples/pythonGrammarParser.py +++ b/examples/pythonGrammarParser.py @@ -5,7 +5,7 @@ from pyparsing import *
-# should probably read this from the Grammar file provided with the Python source, but
+# should probably read this from the Grammar file provided with the Python source, but
# this just skips that step and inlines the bnf text directly - this grammar was taken from
# Python 2.4.1
#
@@ -135,15 +135,15 @@ class SemanticGroup(object): self.contents = contents
while self.contents[-1].__class__ == self.__class__:
self.contents = self.contents[:-1] + self.contents[-1].contents
-
+
def __str__(self):
- return "{}({})".format(self.label,
+ return "{}({})".format(self.label,
" ".join([isinstance(c,str) and c or str(c) for c in self.contents]) )
-
+
class OrList(SemanticGroup):
label = "OR"
pass
-
+
class AndList(SemanticGroup):
label = "AND"
pass
@@ -151,7 +151,7 @@ class AndList(SemanticGroup): class OptionalGroup(SemanticGroup):
label = "OPT"
pass
-
+
class Atom(SemanticGroup):
def __init__(self,contents):
if len(contents) > 1:
@@ -162,10 +162,10 @@ class Atom(SemanticGroup): self.contents = contents
else:
self.contents = contents[0]
-
+
def __str__(self):
return "{}{}".format(self.rep, self.contents)
-
+
def makeGroupObject(cls):
def groupAction(s,l,t):
try:
diff --git a/examples/rangeCheck.py b/examples/rangeCheck.py index b89a1e3..219defa 100644 --- a/examples/rangeCheck.py +++ b/examples/rangeCheck.py @@ -1,6 +1,6 @@ # rangeCheck.py
#
-# A sample program showing how parse actions can convert parsed
+# A sample program showing how parse actions can convert parsed
# strings into a data type or object, and to validate the parsed value.
#
# Updated to use new addCondition method and expr() copy.
@@ -38,7 +38,7 @@ integer.setParseAction(lambda t:int(t[0])) month = ranged_value(integer, 1, 12)
day = ranged_value(integer, 1, 31)
year = ranged_value(integer, 2000, None)
-
+
SLASH = Suppress('/')
dateExpr = year("year") + SLASH + month("month") + Optional(SLASH + day("day"))
dateExpr.setName("date")
@@ -58,5 +58,3 @@ dateExpr.runTests(""" 2004/2/29
2004/2
1999/12/31""")
-
-
diff --git a/examples/readJson.py b/examples/readJson.py index deca53b..f691ea5 100644 --- a/examples/readJson.py +++ b/examples/readJson.py @@ -1,10 +1,9 @@ -
#~ url = "http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails"
-#~ params = {'format':'json'}
-#~ import urllib
-#~ eparams = urllib.urlencode(params)
-#~ import urllib2
-#~ request = urllib2.Request(url,eparams)
+#~ params = {'format':'json'}
+#~ import urllib
+#~ eparams = urllib.urlencode(params)
+#~ import urllib2
+#~ request = urllib2.Request(url,eparams)
#~ response = urllib2.urlopen(request)
#~ s = response.read()
#~ response.close()
diff --git a/examples/removeLineBreaks.py b/examples/removeLineBreaks.py index ba4b498..a94dd35 100644 --- a/examples/removeLineBreaks.py +++ b/examples/removeLineBreaks.py @@ -3,7 +3,7 @@ # Demonstration of the pyparsing module, converting text files
# with hard line-breaks to text files with line breaks only
# between paragraphs. (Helps when converting downloads from Project
-# Gutenberg - http://www.gutenberg.org - to import to word processing apps
+# Gutenberg - http://www.gutenberg.org - to import to word processing apps
# that can reformat paragraphs once hard line-breaks are removed.)
#
# Uses parse actions and transformString to remove unwanted line breaks,
diff --git a/examples/romanNumerals.py b/examples/romanNumerals.py index 27361f0..536fbb0 100644 --- a/examples/romanNumerals.py +++ b/examples/romanNumerals.py @@ -7,7 +7,7 @@ from pyparsing import * def romanNumeralLiteral(numeralString, value):
return Literal(numeralString).setParseAction(replaceWith(value))
-
+
one = romanNumeralLiteral("I",1)
four = romanNumeralLiteral("IV",4)
five = romanNumeralLiteral("V",5)
@@ -22,8 +22,8 @@ fivehundred = romanNumeralLiteral("D",500) ninehundred = romanNumeralLiteral("CM",900)
onethousand = romanNumeralLiteral("M",1000)
-numeral = ( onethousand | ninehundred | fivehundred | fourhundred |
- onehundred | ninety | fifty | forty | ten | nine | five |
+numeral = ( onethousand | ninehundred | fivehundred | fourhundred |
+ onehundred | ninety | fifty | forty | ten | nine | five |
four | one ).leaveWhitespace()
romanNumeral = OneOrMore(numeral).setParseAction( lambda s,l,t : sum(t) )
@@ -34,7 +34,7 @@ def makeRomanNumeral(n): n -= limit
s += c
return n,s
-
+
ret = ""
while n >= 1000: n,ret = addDigit(n,1000,"M",ret)
while n >= 900: n,ret = addDigit(n, 900,"CM",ret)
@@ -66,9 +66,3 @@ test("XIV") test("XIX")
test("MCMLXXX")
test("MMVI")
-
-
-
-
-
-
diff --git a/examples/scanExamples.py b/examples/scanExamples.py index 24ae0e7..4ee62a1 100644 --- a/examples/scanExamples.py +++ b/examples/scanExamples.py @@ -28,8 +28,8 @@ ident = Word(alphas, alphanums+"_") macroDef = Literal("#define") + ident.setResultsName("name") + "=" + restOfLine.setResultsName("value")
for t,s,e in macroDef.scanString( testData ):
print(t.name,":", t.value)
-
-# or a quick way to make a dictionary of the names and values
+
+# or a quick way to make a dictionary of the names and values
# (return only key and value tokens, and construct dict from key-value pairs)
# - empty ahead of restOfLine advances past leading whitespace, does implicit lstrip during parsing
macroDef = Suppress("#define") + ident + Suppress("=") + empty + restOfLine
@@ -48,8 +48,8 @@ scopedIdent.setParseAction(lambda t: "_".join(t)) print("(replace namespace-scoped names with C-compatible names)")
print(scopedIdent.transformString( testData ))
-
-
+
+
# or a crude pre-processor (use parse actions to replace matching text)
def substituteMacro(s,l,t):
if t[0] in macros:
diff --git a/examples/searchParserAppDemo.py b/examples/searchParserAppDemo.py index 021428d..d1bf8ba 100644 --- a/examples/searchParserAppDemo.py +++ b/examples/searchParserAppDemo.py @@ -3,7 +3,7 @@ from searchparser import SearchQueryParser products = [ "grape juice", "grape jelly", "orange juice", "orange jujubees",
"strawberry jam", "prune juice", "prune butter", "orange marmalade",
"grapefruit juice" ]
-
+
class FruitSearchParser(SearchQueryParser):
def GetWord(self, word):
return { p for p in products if p.startswith(word + " ") }
diff --git a/examples/searchparser.py b/examples/searchparser.py index 36e3cd7..d645a1f 100644 --- a/examples/searchparser.py +++ b/examples/searchparser.py @@ -2,7 +2,7 @@ version 2006-03-09
-This search query parser uses the excellent Pyparsing module
+This search query parser uses the excellent Pyparsing module
(http://pyparsing.sourceforge.net/) to parse search queries by users.
It handles:
@@ -30,7 +30,7 @@ are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
+ this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Estrate nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
@@ -41,10 +41,10 @@ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
CONTRIBUTORS:
@@ -72,12 +72,12 @@ class SearchQueryParser: 'wordwildcard': self.evaluateWordWildcard,
}
self._parser = self.parser()
-
+
def parser(self):
"""
This function returns a parser.
The grammar should be like most full text search engines (Google, Tsearch, Lucene).
-
+
Grammar:
- a query consists of alphanumeric words, with an optional '*' wildcard
at the end of a word
@@ -89,19 +89,19 @@ class SearchQueryParser: - if an operator is missing, use an 'and' operator
"""
operatorOr = Forward()
-
+
operatorWord = Group(Combine(Word(alphanums) + Suppress('*'))).setResultsName('wordwildcard') | \
Group(Word(alphanums)).setResultsName('word')
-
+
operatorQuotesContent = Forward()
operatorQuotesContent << (
(operatorWord + operatorQuotesContent) | operatorWord
)
-
+
operatorQuotes = Group(
Suppress('"') + operatorQuotesContent + Suppress('"')
).setResultsName("quotes") | operatorWord
-
+
operatorParenthesis = Group(
(Suppress("(") + operatorOr + Suppress(")"))
).setResultsName("parenthesis") | operatorQuotes
@@ -117,7 +117,7 @@ class SearchQueryParser: ).setResultsName("and") | Group(
operatorNot + OneOrMore(~oneOf("and or") + operatorAnd)
).setResultsName("and") | operatorNot)
-
+
operatorOr << (Group(
operatorAnd + Suppress(Keyword("or", caseless=True)) + operatorOr
).setResultsName("or") | operatorAnd)
@@ -158,7 +158,7 @@ class SearchQueryParser: def evaluateWordWildcard(self, argument):
return self.GetWordWildcard(argument[0])
-
+
def evaluate(self, argument):
return self._methods[argument.getName()](argument)
@@ -230,7 +230,7 @@ class ParserTest(SearchQueryParser): 7: 'nothing',
8: 'helper',
}
-
+
index = {
'help': {1, 2, 4, 5},
'me': {2},
@@ -264,7 +264,7 @@ class ParserTest(SearchQueryParser): if self.docs[item].count(search_string):
result.add(item)
return result
-
+
def GetNot(self, not_set):
all = set(list(self.docs.keys()))
return all.difference(not_set)
@@ -284,7 +284,7 @@ class ParserTest(SearchQueryParser): print('>>>>>>>>>>>>>>>>>>>>>>Test ERROR<<<<<<<<<<<<<<<<<<<<<')
print('')
return all_ok
-
+
if __name__=='__main__':
if ParserTest().Test():
print('All tests OK')
diff --git a/examples/select_parser.py b/examples/select_parser.py index 5925ad8..7b3727e 100644 --- a/examples/select_parser.py +++ b/examples/select_parser.py @@ -11,22 +11,22 @@ LPAR,RPAR,COMMA = map(Suppress,"(),") select_stmt = Forward().setName("select statement")
# keywords
-(UNION, ALL, AND, INTERSECT, EXCEPT, COLLATE, ASC, DESC, ON, USING, NATURAL, INNER,
+(UNION, ALL, AND, INTERSECT, EXCEPT, COLLATE, ASC, DESC, ON, USING, NATURAL, INNER,
CROSS, LEFT, OUTER, JOIN, AS, INDEXED, NOT, SELECT, DISTINCT, FROM, WHERE, GROUP, BY,
- HAVING, ORDER, BY, LIMIT, OFFSET, OR) = map(CaselessKeyword, """UNION, ALL, AND, INTERSECT,
- EXCEPT, COLLATE, ASC, DESC, ON, USING, NATURAL, INNER, CROSS, LEFT, OUTER, JOIN, AS, INDEXED, NOT, SELECT,
+ HAVING, ORDER, BY, LIMIT, OFFSET, OR) = map(CaselessKeyword, """UNION, ALL, AND, INTERSECT,
+ EXCEPT, COLLATE, ASC, DESC, ON, USING, NATURAL, INNER, CROSS, LEFT, OUTER, JOIN, AS, INDEXED, NOT, SELECT,
DISTINCT, FROM, WHERE, GROUP, BY, HAVING, ORDER, BY, LIMIT, OFFSET, OR""".replace(",","").split())
(CAST, ISNULL, NOTNULL, NULL, IS, BETWEEN, ELSE, END, CASE, WHEN, THEN, EXISTS,
- COLLATE, IN, LIKE, GLOB, REGEXP, MATCH, ESCAPE, CURRENT_TIME, CURRENT_DATE,
- CURRENT_TIMESTAMP) = map(CaselessKeyword, """CAST, ISNULL, NOTNULL, NULL, IS, BETWEEN, ELSE,
- END, CASE, WHEN, THEN, EXISTS, COLLATE, IN, LIKE, GLOB, REGEXP, MATCH, ESCAPE,
+ COLLATE, IN, LIKE, GLOB, REGEXP, MATCH, ESCAPE, CURRENT_TIME, CURRENT_DATE,
+ CURRENT_TIMESTAMP) = map(CaselessKeyword, """CAST, ISNULL, NOTNULL, NULL, IS, BETWEEN, ELSE,
+ END, CASE, WHEN, THEN, EXISTS, COLLATE, IN, LIKE, GLOB, REGEXP, MATCH, ESCAPE,
CURRENT_TIME, CURRENT_DATE, CURRENT_TIMESTAMP""".replace(",","").split())
-keyword = MatchFirst((UNION, ALL, INTERSECT, EXCEPT, COLLATE, ASC, DESC, ON, USING, NATURAL, INNER,
+keyword = MatchFirst((UNION, ALL, INTERSECT, EXCEPT, COLLATE, ASC, DESC, ON, USING, NATURAL, INNER,
CROSS, LEFT, OUTER, JOIN, AS, INDEXED, NOT, SELECT, DISTINCT, FROM, WHERE, GROUP, BY,
HAVING, ORDER, BY, LIMIT, OFFSET, CAST, ISNULL, NOTNULL, NULL, IS, BETWEEN, ELSE, END, CASE, WHEN, THEN, EXISTS,
- COLLATE, IN, LIKE, GLOB, REGEXP, MATCH, ESCAPE, CURRENT_TIME, CURRENT_DATE,
+ COLLATE, IN, LIKE, GLOB, REGEXP, MATCH, ESCAPE, CURRENT_TIME, CURRENT_DATE,
CURRENT_TIMESTAMP))
-
+
identifier = ~keyword + Word(alphas, alphanums+"_")
collation_name = identifier.copy()
column_name = identifier.copy()
@@ -88,20 +88,20 @@ join_constraint = Group(Optional(ON + expr | USING + LPAR + Group(delimitedList( join_op = COMMA | Group(Optional(NATURAL) + Optional(INNER | CROSS | LEFT + OUTER | LEFT | OUTER) + JOIN)
join_source = Forward()
-single_source = ( (Group(database_name("database") + "." + table_name("table*")) | table_name("table*")) +
+single_source = ( (Group(database_name("database") + "." + table_name("table*")) | table_name("table*")) +
Optional(Optional(AS) + table_alias("table_alias*")) +
- Optional(INDEXED + BY + index_name("name") | NOT + INDEXED)("index") |
- (LPAR + select_stmt + RPAR + Optional(Optional(AS) + table_alias)) |
+ Optional(INDEXED + BY + index_name("name") | NOT + INDEXED)("index") |
+ (LPAR + select_stmt + RPAR + Optional(Optional(AS) + table_alias)) |
(LPAR + join_source + RPAR) )
-join_source << (Group(single_source + OneOrMore(join_op + single_source + join_constraint)) |
+join_source << (Group(single_source + OneOrMore(join_op + single_source + join_constraint)) |
single_source)
result_column = "*" | table_name + "." + "*" | Group(expr + Optional(Optional(AS) + column_alias))
select_core = (SELECT + Optional(DISTINCT | ALL) + Group(delimitedList(result_column))("columns") +
Optional(FROM + join_source("from*")) +
Optional(WHERE + expr("where_expr")) +
- Optional(GROUP + BY + Group(delimitedList(ordering_term))("group_by_terms") +
+ Optional(GROUP + BY + Group(delimitedList(ordering_term))("group_by_terms") +
Optional(HAVING + expr("having_expr"))))
select_stmt << (select_core + ZeroOrMore(compound_operator + select_core) +
diff --git a/examples/sexpParser.py b/examples/sexpParser.py index 963d153..86fb089 100644 --- a/examples/sexpParser.py +++ b/examples/sexpParser.py @@ -5,8 +5,8 @@ #
# Updates:
# November, 2011 - fixed errors in precedence of alternatives in simpleString;
-# fixed exception raised in verifyLen to properly signal the input string
-# and exception location so that markInputline works correctly; fixed
+# fixed exception raised in verifyLen to properly signal the input string
+# and exception location so that markInputline works correctly; fixed
# definition of decimal to accept a single '0' and optional leading '-'
# sign; updated tests to improve parser coverage
#
@@ -17,7 +17,7 @@ BNF reference: http://theory.lcs.mit.edu/~rivest/sexp.txt <sexp> :: <string> | <list>
<string> :: <display>? <simple-string> ;
-<simple-string> :: <raw> | <token> | <base-64> | <hexadecimal> |
+<simple-string> :: <raw> | <token> | <base-64> | <hexadecimal> |
<quoted-string> ;
<display> :: "[" <simple-string> "]" ;
<raw> :: <decimal> ":" <bytes> ;
@@ -27,7 +27,7 @@ BNF reference: http://theory.lcs.mit.edu/~rivest/sexp.txt <token> :: <tokenchar>+ ;
<base-64> :: <decimal>? "|" ( <base-64-char> | <whitespace> )* "|" ;
<hexadecimal> :: "#" ( <hex-digit> | <white-space> )* "#" ;
-<quoted-string> :: <decimal>? <quoted-string-body>
+<quoted-string> :: <decimal>? <quoted-string-body>
<quoted-string-body> :: "\"" <bytes> "\""
<list> :: "(" ( <sexp> | <whitespace> )* ")" ;
<whitespace> :: <whitespace-char>* ;
@@ -65,11 +65,11 @@ hexadecimal = ("#" + OneOrMore(Word(hexnums)) + "#")\ bytes = Word(printables)
raw = Group(decimal("len") + Suppress(":") + bytes).setParseAction(verifyLen)
token = Word(alphanums + "-./_:*+=")
-base64_ = Group(Optional(decimal|hexadecimal,default=None)("len") + VBAR
+base64_ = Group(Optional(decimal|hexadecimal,default=None)("len") + VBAR
+ OneOrMore(Word( alphanums +"+/=" )).setParseAction(lambda t: b64decode("".join(t)))
+ VBAR).setParseAction(verifyLen)
-
-qString = Group(Optional(decimal,default=None)("len") +
+
+qString = Group(Optional(decimal,default=None)("len") +
dblQuotedString.setParseAction(removeQuotes)).setParseAction(verifyLen)
simpleString = base64_ | raw | decimal | token | hexadecimal | qString
@@ -86,7 +86,7 @@ string_ = Optional(display) + simpleString sexp = Forward()
sexpList = Group(LPAR + ZeroOrMore(sexp) + RPAR)
sexp << ( string_ | sexpList )
-
+
######### Test data ###########
test00 = """(snicker "abc" (#03# |YWJj|))"""
test01 = """(certificate
@@ -142,14 +142,14 @@ test07 = """(defun factorial (x) test51 = """(2:XX "abc" (#30# |YWJj|))"""
test51error = """(3:XX "abc" (#30# |YWJj|))"""
-test52 = """
- (and
- (or (> uid 1000)
- (!= gid 20)
- )
- (> quota 5.0e+03)
- )
- """
+test52 = """
+ (and
+ (or (> uid 1000)
+ (!= gid 20)
+ )
+ (> quota 5.0e+03)
+ )
+ """
# Run tests
t = None
diff --git a/examples/shapes.py b/examples/shapes.py index c5f4867..73ed334 100644 --- a/examples/shapes.py +++ b/examples/shapes.py @@ -1,6 +1,6 @@ # shapes.py
#
-# A sample program showing how parse actions can convert parsed
+# A sample program showing how parse actions can convert parsed
# strings into a data type or object.
#
# Copyright 2012, Paul T. McGuire
@@ -13,7 +13,7 @@ class Shape(object): def area(self):
raise NotImplementedException()
-
+
def __str__(self):
return "<{}>: {}".format(self.__class__.__name__, self.__dict__)
diff --git a/examples/simpleArith.py b/examples/simpleArith.py index 825956b..af05373 100644 --- a/examples/simpleArith.py +++ b/examples/simpleArith.py @@ -34,7 +34,7 @@ factop = Literal('!') # - rightLeftAssoc is the indicator whether the operator is
# right or left associative, using the pyparsing-defined
# constants opAssoc.RIGHT and opAssoc.LEFT.
-# - parseAction is the parse action to be associated with
+# - parseAction is the parse action to be associated with
# expressions matching this operator expression (the
# parse action tuple member may be omitted)
# 3. Call infixNotation passing the operand expression and
@@ -42,7 +42,7 @@ factop = Literal('!') # as the generated pyparsing expression. You can then use
# this expression to parse input strings, or incorporate it
# into a larger, more complex grammar.
-#
+#
expr = infixNotation( operand,
[("!", 1, opAssoc.LEFT),
("^", 2, opAssoc.RIGHT),
@@ -63,5 +63,4 @@ test = ["9 + 2 + 3", for t in test:
print(t)
print(expr.parseString(t))
- print('')
-
+ print('')
diff --git a/examples/simpleBool.py b/examples/simpleBool.py index 5f355b7..d1df9a5 100644 --- a/examples/simpleBool.py +++ b/examples/simpleBool.py @@ -98,5 +98,3 @@ if __name__ == "__main__": res = boolExpr.parseString(t)[0]
success = "PASS" if bool(res) == expected else "FAIL"
print (t,'\n', res, '=', bool(res),'\n', success, '\n')
-
-
diff --git a/examples/simpleSQL.py b/examples/simpleSQL.py index 6cde6ce..18e93a0 100644 --- a/examples/simpleSQL.py +++ b/examples/simpleSQL.py @@ -35,11 +35,11 @@ whereCondition = Group( ( columnName + in_ + "(" + selectStmt + ")" ) |
( "(" + whereExpression + ")" )
)
-whereExpression << whereCondition + ZeroOrMore( ( and_ | or_ ) + whereExpression )
+whereExpression << whereCondition + ZeroOrMore( ( and_ | or_ ) + whereExpression )
# define the grammar
-selectStmt <<= (SELECT + ('*' | columnNameList)("columns") +
- FROM + tableNameList( "tables" ) +
+selectStmt <<= (SELECT + ('*' | columnNameList)("columns") +
+ FROM + tableNameList( "tables" ) +
Optional(Group(WHERE + whereExpression), "")("where"))
simpleSQL = selectStmt
@@ -61,7 +61,7 @@ if __name__ == "__main__": Select A,B,C from Sys.dual
- Select A, B, C from Sys.dual, Table2
+ Select A, B, C from Sys.dual, Table2
# FAIL - invalid SELECT keyword
Xelect A, B, C from Sys.dual
diff --git a/examples/simpleWiki.py b/examples/simpleWiki.py index 1813432..4ec3b71 100644 --- a/examples/simpleWiki.py +++ b/examples/simpleWiki.py @@ -12,7 +12,7 @@ def convertToHTML(opening,closing): def conversionParseAction(s,l,t):
return opening + t[0] + closing
return conversionParseAction
-
+
italicized = QuotedString("*").setParseAction(convertToHTML("<I>","</I>"))
bolded = QuotedString("**").setParseAction(convertToHTML("<B>","</B>"))
boldItalicized = QuotedString("***").setParseAction(convertToHTML("<B><I>","</I></B>"))
@@ -22,7 +22,7 @@ def convertToHTML_A(s,l,t): except ValueError:
raise ParseFatalException(s,l,"invalid URL link reference: " + t[0])
return '<A href="{}">{}</A>'.format(url,text)
-
+
urlRef = QuotedString("{{",endQuoteChar="}}").setParseAction(convertToHTML_A)
wikiMarkup = urlRef | boldItalicized | bolded | italicized
diff --git a/examples/snmp_api.h b/examples/snmp_api.h index d75cb12..fc802d1 100644 --- a/examples/snmp_api.h +++ b/examples/snmp_api.h @@ -13,10 +13,10 @@ #ifndef DONT_SHARE_ERROR_WITH_OTHER_THREADS
#define SET_SNMP_ERROR(x) snmp_errno=(x)
#else
-#define SET_SNMP_ERROR(x)
+#define SET_SNMP_ERROR(x)
#endif
-
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -109,7 +109,7 @@ struct snmp_pdu { long version;
int command; /* Type of this PDU */
long reqid; /* Request id - note: not incremented on retries */
- long msgid; /* Message id for V3 messages
+ long msgid; /* Message id for V3 messages
* note: incremented for each retry */
long transid; /* Unique ID for incoming transactions */
long sessid; /* Session id for AgentX messages */
@@ -291,7 +291,7 @@ extern void snmp_set_detail (const char *); #define REPORT_usmStatsUnsupportedSecLevels_NUM 1
#define REPORT_usmStatsNotInTimeWindows_NUM 2
#define REPORT_usmStatsUnknownUserNames_NUM 3
-#define REPORT_usmStatsUnknownEngineIDs_NUM 4
+#define REPORT_usmStatsUnknownEngineIDs_NUM 4
#define REPORT_usmStatsWrongDigests_NUM 5
#define REPORT_usmStatsDecryptionErrors_NUM 6
@@ -478,7 +478,7 @@ int snmp_send (struct snmp_session *, struct snmp_pdu *); * On any error, 0 is returned.
* The pdu is freed by snmp_send() unless a failure occured.
*/
-int snmp_async_send (struct snmp_session *, struct snmp_pdu *,
+int snmp_async_send (struct snmp_session *, struct snmp_pdu *,
snmp_callback, void *);
diff --git a/examples/sparser.py b/examples/sparser.py index c3c3da0..68d8a52 100644 --- a/examples/sparser.py +++ b/examples/sparser.py @@ -2,7 +2,7 @@ """
NAME:
- sparser.py
+ sparser.py
SYNOPSIS:
sparser.py [options] filename
@@ -64,7 +64,7 @@ debug_p = 0 #---positional args, default is empty---
-pargs = []
+pargs = []
#---other---
@@ -86,7 +86,7 @@ def fatal(ftn, txt): """If can't continue."""
msg = "{}.{}:FATAL:{}\n".format(modname, ftn, txt)
raise SystemExit(msg)
-
+
def usage():
"""Prints the docstring."""
print(__doc__)
@@ -129,10 +129,10 @@ class ParseFileLineByLine: or '~user' to indicate a home directory, as well as URLs (for reading
only).
- Constructor:
+ Constructor:
ParseFileLineByLine(|filename|, |mode|='"r"'), where |filename| is the name
of the file (or a URL) and |mode| is one of '"r"' (read), '"w"' (write) or
- '"a"' (append, not supported for .Z files).
+ '"a"' (append, not supported for .Z files).
"""
def __init__(self, filename, mode = 'r'):
@@ -154,27 +154,27 @@ class ParseFileLineByLine: raise IOError(2, 'No such file or directory: ' + filename)
filen, file_extension = os.path.splitext(filename)
command_dict = {
- ('.Z', 'r'):
+ ('.Z', 'r'):
"self.file = os.popen('uncompress -c ' + filename, mode)",
- ('.gz', 'r'):
+ ('.gz', 'r'):
"self.file = gzip.GzipFile(filename, 'rb')",
- ('.bz2', 'r'):
+ ('.bz2', 'r'):
"self.file = os.popen('bzip2 -dc ' + filename, mode)",
- ('.Z', 'w'):
+ ('.Z', 'w'):
"self.file = os.popen('compress > ' + filename, mode)",
- ('.gz', 'w'):
+ ('.gz', 'w'):
"self.file = gzip.GzipFile(filename, 'wb')",
- ('.bz2', 'w'):
+ ('.bz2', 'w'):
"self.file = os.popen('bzip2 > ' + filename, mode)",
- ('.Z', 'a'):
+ ('.Z', 'a'):
"raise IOError, (0, 'Can\'t append to .Z files')",
- ('.gz', 'a'):
+ ('.gz', 'a'):
"self.file = gzip.GzipFile(filename, 'ab')",
- ('.bz2', 'a'):
+ ('.bz2', 'a'):
"raise IOError, (0, 'Can\'t append to .bz2 files')",
}
- exec(command_dict.get((file_extension, mode),
+ exec(command_dict.get((file_extension, mode),
'self.file = open(filename, mode)'))
self.grammar = None
@@ -211,54 +211,54 @@ class ParseFileLineByLine: decimal_sep = "."
sign = oneOf("+ -")
# part of printables without decimal_sep, +, -
- special_chars = string.replace('!"#$%&\'()*,./:;<=>?@[\\]^_`{|}~',
- decimal_sep, "")
+ special_chars = string.replace('!"#$%&\'()*,./:;<=>?@[\\]^_`{|}~',
+ decimal_sep, "")
integer = ToInteger(
- Combine(Optional(sign) +
+ Combine(Optional(sign) +
Word(nums))).setName("integer")
positive_integer = ToInteger(
- Combine(Optional("+") +
+ Combine(Optional("+") +
Word(nums))).setName("integer")
negative_integer = ToInteger(
- Combine("-" +
+ Combine("-" +
Word(nums))).setName("integer")
real = ToFloat(
- Combine(Optional(sign) +
- Word(nums) +
- decimal_sep +
- Optional(Word(nums)) +
- Optional(oneOf("E e") +
+ Combine(Optional(sign) +
+ Word(nums) +
+ decimal_sep +
+ Optional(Word(nums)) +
+ Optional(oneOf("E e") +
Word(nums)))).setName("real")
positive_real = ToFloat(
- Combine(Optional("+") +
- Word(nums) +
- decimal_sep +
- Optional(Word(nums)) +
- Optional(oneOf("E e") +
+ Combine(Optional("+") +
+ Word(nums) +
+ decimal_sep +
+ Optional(Word(nums)) +
+ Optional(oneOf("E e") +
Word(nums)))).setName("real")
negative_real = ToFloat(
- Combine("-" +
- Word(nums) +
- decimal_sep +
- Optional(Word(nums)) +
- Optional(oneOf("E e") +
+ Combine("-" +
+ Word(nums) +
+ decimal_sep +
+ Optional(Word(nums)) +
+ Optional(oneOf("E e") +
Word(nums)))).setName("real")
qString = ( sglQuotedString | dblQuotedString ).setName("qString")
-
+
# add other characters we should skip over between interesting fields
integer_junk = Optional(
Suppress(
- Word(alphas +
- special_chars +
+ Word(alphas +
+ special_chars +
decimal_sep))).setName("integer_junk")
real_junk = Optional(
Suppress(
- Word(alphas +
+ Word(alphas +
special_chars))).setName("real_junk")
qString_junk = SkipTo(qString).setName("qString_junk")
# Now that 'integer', 'real', and 'qString' have been assigned I can
- # execute the definition file.
+ # execute the definition file.
exec(compile(open(self.parsedef).read(), self.parsedef, 'exec'))
# Build the grammar, combination of the 'integer', 'real, 'qString',
@@ -337,7 +337,7 @@ def main(pargs): for i in fp:
print(i)
-
+
#-------------------------
if __name__ == '__main__':
ftn = "main"
@@ -361,5 +361,5 @@ if __name__ == '__main__': #===Revision Log===
#Created by mkpythonproj:
-#2006-02-06 Tim Cera
+#2006-02-06 Tim Cera
#
diff --git a/examples/sql2dot.py b/examples/sql2dot.py index 1156207..aa86c40 100644 --- a/examples/sql2dot.py +++ b/examples/sql2dot.py @@ -2,7 +2,7 @@ # sql2dot.py
#
-# Creates table graphics by parsing SQL table DML commands and
+# Creates table graphics by parsing SQL table DML commands and
# generating DOT language output.
#
# Adapted from a post at http://energyblog.blogspot.com/2006/04/blog-post_20.html.
@@ -38,15 +38,15 @@ class_id integer alter table only student_registrations
add constraint students_link
- foreign key
+ foreign key
(student_id) references students(student_id);
alter table only student_registrations
- add constraint classes_link
- foreign key
+ add constraint classes_link
+ foreign key
(class_id) references classes(class_id);
""".upper()
-
+
from pyparsing import Literal, CaselessLiteral, Word, delimitedList \
,Optional, Combine, Group, alphas, nums, alphanums, Forward \
, oneOf, sglQuotedString, OneOrMore, ZeroOrMore, CharsNotIn \
@@ -55,7 +55,7 @@ from pyparsing import Literal, CaselessLiteral, Word, delimitedList \ skobki = "(" + ZeroOrMore(CharsNotIn(")")) + ")"
field_def = OneOrMore(Word(alphas,alphanums+"_\"':-") | skobki)
-def field_act(s,loc,tok):
+def field_act(s,loc,tok):
return ("<"+tok[0]+"> " + " ".join(tok)).replace("\"","\\\"")
field_def.setParseAction(field_act)
@@ -75,7 +75,7 @@ create_table_def.setParseAction(create_table_act) add_fkey_def=Literal("ALTER")+"TABLE"+"ONLY" + Word(alphanums+"_").setResultsName("fromtable") + "ADD" \
+ "CONSTRAINT" + Word(alphanums+"_") + "FOREIGN"+"KEY"+"("+Word(alphanums+"_").setResultsName("fromcolumn")+")" \
- +"REFERENCES"+Word(alphanums+"_").setResultsName("totable")+"("+Word(alphanums+"_").setResultsName("tocolumn")+")"+";"
+ +"REFERENCES"+Word(alphanums+"_").setResultsName("totable")+"("+Word(alphanums+"_").setResultsName("tocolumn")+")"+";"
def add_fkey_act(toks):
return """ "%(fromtable)s":%(fromcolumn)s -> "%(totable)s":%(tocolumn)s """ % toks
@@ -90,7 +90,7 @@ statement_def = comment_def | create_table_def | add_fkey_def | other_statement defs = OneOrMore(statement_def)
print("""digraph g { graph [ rankdir = "LR" ]; """)
-for i in defs.parseString(sampleSQL):
- if i!="":
+for i in defs.parseString(sampleSQL):
+ if i!="":
print(i)
-print("}")
\ No newline at end of file +print("}")
diff --git a/examples/stackish.py b/examples/stackish.py index f80b4d6..3fa98f4 100644 --- a/examples/stackish.py +++ b/examples/stackish.py @@ -1,31 +1,31 @@ # stackish.py
#
-# Stackish is a data representation syntax, similar to JSON or YAML. For more info on
+# Stackish is a data representation syntax, similar to JSON or YAML. For more info on
# stackish, see http://www.savingtheinternetwithhate.com/stackish.html
#
# Copyright 2008, Paul McGuire
#
"""
-NUMBER A simple integer type that's just any series of digits.
-FLOAT A simple floating point type.
-STRING A string is double quotes with anything inside that's not a " or
- newline character. You can include \n and \" to include these
- characters.
-MARK Marks a point in the stack that demarcates the boundary for a nested
- group.
-WORD Marks the root node of a group, with the other end being the nearest
- MARK.
-GROUP Acts as the root node of an anonymous group.
-ATTRIBUTE Assigns an attribute name to the previously processed node.
- This means that just about anything can be an attribute, unlike in XML.
-BLOB A BLOB is unique to Stackish and allows you to record any content
+NUMBER A simple integer type that's just any series of digits.
+FLOAT A simple floating point type.
+STRING A string is double quotes with anything inside that's not a " or
+ newline character. You can include \n and \" to include these
+ characters.
+MARK Marks a point in the stack that demarcates the boundary for a nested
+ group.
+WORD Marks the root node of a group, with the other end being the nearest
+ MARK.
+GROUP Acts as the root node of an anonymous group.
+ATTRIBUTE Assigns an attribute name to the previously processed node.
+ This means that just about anything can be an attribute, unlike in XML.
+BLOB A BLOB is unique to Stackish and allows you to record any content
(even binary content) inside the structure. This is done by pre-
- sizing the data with the NUMBER similar to Dan Bernstein's netstrings
- setup.
-SPACE White space is basically ignored. This is interesting because since
- Stackish is serialized consistently this means you can use \n as the
- separation character and perform reasonable diffs on two structures.
+ sizing the data with the NUMBER similar to Dan Bernstein's netstrings
+ setup.
+SPACE White space is basically ignored. This is interesting because since
+ Stackish is serialized consistently this means you can use \n as the
+ separation character and perform reasonable diffs on two structures.
"""
from pyparsing import Suppress,Word,nums,alphas,alphanums,Combine,oneOf,\
@@ -45,7 +45,7 @@ strBody = Forward() def setBodyLength(tokens):
strBody << Word(srange(r'[\0x00-\0xffff]'), exact=int(tokens[0]))
return ""
-BLOB = Combine(QUOTE + Word(nums).setParseAction(setBodyLength) +
+BLOB = Combine(QUOTE + Word(nums).setParseAction(setBodyLength) +
COLON + strBody + QUOTE)
item = Forward()
@@ -55,13 +55,13 @@ def assignUsing(s): tokens[tokens[s]] = tokens[0]
del tokens[s]
return assignPA
-GROUP = (MARK +
- Group( ZeroOrMore(
- (item +
+GROUP = (MARK +
+ Group( ZeroOrMore(
+ (item +
Optional(ATTRIBUTE)("attr")
).setParseAction(assignUsing("attr"))
)
- ) +
+ ) +
( WORD("name") | UNMARK )
).setParseAction(assignUsing("name"))
item << (NUMBER | FLOAT | STRING | BLOB | GROUP )
diff --git a/examples/stateMachine2.py b/examples/stateMachine2.py index 748bb8b..21e0545 100644 --- a/examples/stateMachine2.py +++ b/examples/stateMachine2.py @@ -1,5 +1,5 @@ # stateMachine.py
-#
+#
# module to define .pystate import handler
#
#import imputil
@@ -18,9 +18,9 @@ from pyparsing import Word, Group, ZeroOrMore, alphas, \ ident = Word(alphas+"_", alphanums+"_$")
-pythonKeywords = """and as assert break class continue def
- del elif else except exec finally for from global if import
- in is lambda None not or pass print raise return try while with
+pythonKeywords = """and as assert break class continue def
+ del elif else except exec finally for from global if import
+ in is lambda None not or pass print raise return try while with
yield True False"""
pythonKeywords = set(pythonKeywords.split())
def no_keywords_allowed(s,l,t):
@@ -46,7 +46,7 @@ namedStateMachine = Keyword("statemachine") + \ def expand_state_definition(source, loc, tokens):
indent = " " * (col(loc,source)-1)
statedef = []
-
+
# build list of states
states = set()
fromTo = {}
@@ -54,7 +54,7 @@ def expand_state_definition(source, loc, tokens): states.add(tn.fromState)
states.add(tn.toState)
fromTo[tn.fromState] = tn.toState
-
+
# define base class for state classes
baseStateClass = tokens.name + "State"
statedef.extend([
@@ -63,17 +63,17 @@ def expand_state_definition(source, loc, tokens): " return self.__class__.__name__",
" def next_state(self):",
" return self._next_state_class()" ])
-
+
# define all state classes
statedef.extend(
- "class {}({}): pass".format(s,baseStateClass)
+ "class {}({}): pass".format(s,baseStateClass)
for s in states )
statedef.extend(
- "{}._next_state_class = {}".format(s,fromTo[s])
+ "{}._next_state_class = {}".format(s,fromTo[s])
for s in states if s in fromTo )
-
+
return indent + ("\n"+indent).join(statedef)+"\n"
-
+
stateMachine.setParseAction(expand_state_definition)
def expand_named_state_definition(source,loc,tokens):
@@ -82,9 +82,9 @@ def expand_named_state_definition(source,loc,tokens): # build list of states and transitions
states = set()
transitions = set()
-
+
baseStateClass = tokens.name + "State"
-
+
fromTo = {}
for tn in tokens.transitions:
states.add(tn.fromState)
@@ -99,7 +99,7 @@ def expand_named_state_definition(source,loc,tokens): for s in states:
if s not in fromTo:
fromTo[s] = {}
-
+
# define state transition class
statedef.extend([
"class %sTransition:" % baseStateClass,
@@ -107,9 +107,9 @@ def expand_named_state_definition(source,loc,tokens): " return self.transitionName",
])
statedef.extend(
- "{} = {}Transition()".format(tn,baseStateClass)
+ "{} = {}Transition()".format(tn,baseStateClass)
for tn in transitions)
- statedef.extend("{}.transitionName = '{}'".format(tn,tn)
+ statedef.extend("{}.transitionName = '{}'".format(tn,tn)
for tn in transitions)
# define base class for state classes
@@ -128,19 +128,19 @@ def expand_named_state_definition(source,loc,tokens): " def __getattr__(self,name):",
" raise Exception(%s)" % excmsg,
])
-
+
# define all state classes
for s in states:
- statedef.append("class %s(%s): pass" %
+ statedef.append("class %s(%s): pass" %
(s,baseStateClass))
# define state transition maps and transition methods
for s in states:
trns = list(fromTo[s].items())
- statedef.append("%s.tnmap = {%s}" %
+ statedef.append("%s.tnmap = {%s}" %
(s, ",".join("%s:%s" % tn for tn in trns)) )
statedef.extend([
- "%s.%s = staticmethod(lambda : %s())" %
+ "%s.%s = staticmethod(lambda : %s())" %
(s,tn_,to_)
for tn_,to_ in trns
])
@@ -159,7 +159,7 @@ class SuffixImporter(object): the PEP, and also used Doug Hellmann's PyMOTW article `Modules and
Imports`_, as a pattern.
- .. _`Modules and Imports`: http://www.doughellmann.com/PyMOTW/sys/imports.html
+ .. _`Modules and Imports`: http://www.doughellmann.com/PyMOTW/sys/imports.html
Define a subclass that specifies a :attr:`suffix` attribute, and
implements a :meth:`process_filedata` method. Then call the classmethod
@@ -199,7 +199,7 @@ class SuffixImporter(object): checkpath = os.path.join(
dirpath,'{}.{}'.format(fullname,self.suffix))
yield checkpath
-
+
def find_module(self, fullname, path=None):
for checkpath in self.checkpath_iter(fullname):
if os.path.isfile(checkpath):
@@ -237,20 +237,20 @@ class PystateImporter(SuffixImporter): # MATT-NOTE: re-worked :func:`get_state_machine`
# convert any statemachine expressions
- stateMachineExpr = (stateMachine |
+ stateMachineExpr = (stateMachine |
namedStateMachine).ignore(
pythonStyleComment)
generated_code = stateMachineExpr.transformString(data)
if DEBUG: print(generated_code)
- # compile code object from generated code
- # (strip trailing spaces and tabs, compile doesn't like
+ # compile code object from generated code
+ # (strip trailing spaces and tabs, compile doesn't like
# dangling whitespace)
COMPILE_MODE = 'exec'
- codeobj = compile(generated_code.rstrip(" \t"),
- module.__file__,
+ codeobj = compile(generated_code.rstrip(" \t"),
+ module.__file__,
COMPILE_MODE)
exec(codeobj, module.__dict__)
diff --git a/examples/urlExtractor.py b/examples/urlExtractor.py index 10783de..58e74ae 100644 --- a/examples/urlExtractor.py +++ b/examples/urlExtractor.py @@ -23,11 +23,8 @@ with closing(urllib.request.urlopen("http://www.yahoo.com")) as serverListPage: for toks,strt,end in link.scanString(htmlText):
print(toks.asList())
-# Create dictionary from list comprehension, assembled from each pair of tokens returned
+# Create dictionary from list comprehension, assembled from each pair of tokens returned
# from a matched URL.
-pprint.pprint(
+pprint.pprint(
{toks.body: toks.href for toks,strt,end in link.scanString(htmlText)}
)
-
-
-
diff --git a/examples/urlExtractorNew.py b/examples/urlExtractorNew.py index 7d6a1b5..e258408 100644 --- a/examples/urlExtractorNew.py +++ b/examples/urlExtractorNew.py @@ -25,11 +25,8 @@ serverListPage.close() for toks,strt,end in link.scanString(htmlText):
print(toks.startA.href,"->",toks.body)
-# Create dictionary from list comprehension, assembled from each pair of tokens returned
+# Create dictionary from list comprehension, assembled from each pair of tokens returned
# from a matched URL.
-pprint.pprint(
+pprint.pprint(
{ toks.body:toks.startA.href for toks,strt,end in link.scanString(htmlText) }
)
-
-
-
diff --git a/examples/verilogParse.py b/examples/verilogParse.py index 05650df..0c63f19 100644 --- a/examples/verilogParse.py +++ b/examples/verilogParse.py @@ -125,7 +125,7 @@ def Verilog_BNF(): identifier2 = Regex(r"\\\S+").setParseAction(lambda t:t[0][1:]).setName("escapedIdent")#.setDebug()
identifier = identifier1 | identifier2
assert(identifier2 == r'\abc')
-
+
hexnums = nums + "abcdefABCDEF" + "_?"
base = Regex("'[bBoOdDhH]").setName("base")
basedNumber = Combine( Optional( Word(nums + "_") ) + base + Word(hexnums+"xXzZ"),
@@ -557,10 +557,10 @@ def Verilog_BNF(): port = portExpr | Group( ( DOT + identifier + LPAR + portExpr + RPAR ) )
moduleHdr = Group ( oneOf("module macromodule") + identifier +
- Optional( LPAR + Group( Optional( delimitedList(
- Group(oneOf("input output") +
+ Optional( LPAR + Group( Optional( delimitedList(
+ Group(oneOf("input output") +
(netDecl1Arg | netDecl2Arg | netDecl3Arg) ) |
- port ) ) ) +
+ port ) ) ) +
RPAR ) + SEMI ).setName("moduleHdr")
module = Group( moduleHdr +
@@ -710,7 +710,7 @@ else: #~ lp = LineProfiler(ParseResults.__init__)
main()
-
+
#~ lp.print_stats()
#~ import hotshot
#~ p = hotshot.Profile("vparse.prof",1,1)
diff --git a/examples/withAttribute.py b/examples/withAttribute.py index 062c9ae..7fa2bc8 100644 --- a/examples/withAttribute.py +++ b/examples/withAttribute.py @@ -3,7 +3,7 @@ # Copyright, 2007 - Paul McGuire
#
# Simple example of using withAttribute parse action helper
-# to define
+# to define
#
data = """\
<td align=right width=80><font size=2 face="New Times Roman,Times,Serif"> 49.950 </font></td>
diff --git a/examples/wordsToNum.py b/examples/wordsToNum.py index 7cebbff..3d5c4b7 100644 --- a/examples/wordsToNum.py +++ b/examples/wordsToNum.py @@ -68,11 +68,11 @@ mag = Or(makeLit(s,v) for s,v in majorDefinitions) wordprod = lambda t: reduce(mul,t)
wordsum = lambda t: sum(t)
-numPart = (((( units + Optional(hundreds) ).setParseAction(wordprod) +
- Optional(tens)).setParseAction(wordsum)
+numPart = (((( units + Optional(hundreds) ).setParseAction(wordprod) +
+ Optional(tens)).setParseAction(wordsum)
^ tens )
+ Optional(units) ).setParseAction(wordsum)
-numWords = OneOrMore( (numPart + Optional(mag)).setParseAction(wordprod)
+numWords = OneOrMore( (numPart + Optional(mag)).setParseAction(wordprod)
).setParseAction(wordsum) + StringEnd()
numWords.ignore(Literal("-"))
numWords.ignore(CaselessLiteral("and"))
@@ -103,4 +103,4 @@ test("seventy-seven thousand eight hundred and nineteen", 77819) test("seven hundred seventy-seven thousand seven hundred and seventy-seven", 777777)
test("zero", 0)
test("forty two", 42)
-test("fourty two", 42)
\ No newline at end of file +test("fourty two", 42)
|