diff options
author | ptmcg <ptmcg@austin.rr.com> | 2019-01-30 20:41:33 -0600 |
---|---|---|
committer | ptmcg <ptmcg@austin.rr.com> | 2019-01-30 20:41:33 -0600 |
commit | 3157a77c9584a69839db0f8274c87438b912e99b (patch) | |
tree | 5e93a6e21715f9afcbc55eba56f4a5f962b67a46 | |
parent | f10a02039a6039f8a42b0cc99bea51623676cf01 (diff) | |
download | pyparsing-git-3157a77c9584a69839db0f8274c87438b912e99b.tar.gz |
Update examples and unit tests to more preferred coding styles, imports for pyparsing_common as ppc and pyparsing_unicode as ppu
-rw-r--r-- | .idea/pyparsing.iml | 1 | ||||
-rw-r--r-- | examples/datetimeParseActions.py | 13 | ||||
-rw-r--r-- | examples/decaf_parser.py | 5 | ||||
-rw-r--r-- | examples/dictExample.py | 25 | ||||
-rw-r--r-- | examples/dictExample2.py | 4 | ||||
-rw-r--r-- | examples/excelExpr.py | 15 | ||||
-rw-r--r-- | examples/greetingInGreek.py | 4 | ||||
-rw-r--r-- | examples/greetingInKorean.py | 4 | ||||
-rw-r--r-- | examples/holaMundo.py | 4 | ||||
-rw-r--r-- | examples/jsonParser.py | 34 | ||||
-rw-r--r-- | examples/lucene_grammar.py | 57 | ||||
-rw-r--r-- | examples/simpleSQL.py | 10 | ||||
-rw-r--r-- | examples/urlExtractor.py | 4 | ||||
-rw-r--r-- | unitTests.py | 59 |
14 files changed, 124 insertions, 115 deletions
diff --git a/.idea/pyparsing.iml b/.idea/pyparsing.iml index ed99d55..0fbf55e 100644 --- a/.idea/pyparsing.iml +++ b/.idea/pyparsing.iml @@ -2,6 +2,7 @@ <module type="PYTHON_MODULE" version="4"> <component name="NewModuleRootManager"> <content url="file://$MODULE_DIR$"> + <sourceFolder url="file://$MODULE_DIR$/examples/statemachine" isTestSource="false" /> <excludeFolder url="file://$MODULE_DIR$/User_samples" /> <excludeFolder url="file://$MODULE_DIR$/build" /> <excludeFolder url="file://$MODULE_DIR$/dist" /> diff --git a/examples/datetimeParseActions.py b/examples/datetimeParseActions.py index aa9e016..e5ae2b9 100644 --- a/examples/datetimeParseActions.py +++ b/examples/datetimeParseActions.py @@ -6,11 +6,12 @@ # Copyright 2012, Paul T. McGuire
#
from datetime import datetime
-from pyparsing import *
+import pyparsing as pp
+from pyparsing import pyparsing_common as ppc
# define an integer string, and a parse action to convert it
# to an integer at parse time
-integer = Word(nums).setName("integer")
+integer = pp.Word(pp.nums).setName("integer")
def convertToInt(tokens):
# no need to test for validity - we can't get here
# unless tokens[0] contains all numeric digits
@@ -21,7 +22,7 @@ integer.setParseAction(convertToInt) # define a pattern for a year/month/day date
date_expr = integer('year') + '/' + integer('month') + '/' + integer('day')
-date_expr.ignore(pythonStyleComment)
+date_expr.ignore(pp.pythonStyleComment)
def convertToDatetime(s,loc,tokens):
try:
@@ -32,7 +33,7 @@ def convertToDatetime(s,loc,tokens): except Exception as ve:
errmsg = "'%s/%s/%s' is not a valid date, %s" % \
(tokens.year, tokens.month, tokens.day, ve)
- raise ParseException(s, loc, errmsg)
+ raise pp.ParseException(s, loc, errmsg)
date_expr.setParseAction(convertToDatetime)
@@ -51,8 +52,8 @@ date_expr.runTests("""\ # if dates conform to ISO8601, use definitions in pyparsing_common
-date_expr = pyparsing_common.iso8601_date.setParseAction(pyparsing_common.convertToDate())
-date_expr.ignore(pythonStyleComment)
+date_expr = ppc.iso8601_date.setParseAction(ppc.convertToDate())
+date_expr.ignore(pp.pythonStyleComment)
date_expr.runTests("""\
2000-01-01
diff --git a/examples/decaf_parser.py b/examples/decaf_parser.py index c3574b3..e6b1abb 100644 --- a/examples/decaf_parser.py +++ b/examples/decaf_parser.py @@ -41,6 +41,7 @@ Constant ::= intConstant | doubleConstant | boolConstant | stringConstant | null """ import pyparsing as pp +from pyparsing import pyparsing_common as ppc pp.ParserElement.enablePackrat() # keywords @@ -52,8 +53,8 @@ keywords = pp.MatchFirst(list(keywords)) LPAR, RPAR, LBRACE, RBRACE, LBRACK, RBRACK, DOT, EQ, COMMA, SEMI = map(pp.Suppress, "(){}[].=,;") hexConstant = pp.Regex(r"0[xX][0-9a-fA-F]+").addParseAction(lambda t: int(t[0][2:], 16)) -intConstant = hexConstant | pp.pyparsing_common.integer -doubleConstant = pp.pyparsing_common.real +intConstant = hexConstant | ppc.integer +doubleConstant = ppc.real boolConstant = TRUE | FALSE stringConstant = pp.dblQuotedString null = NULL diff --git a/examples/dictExample.py b/examples/dictExample.py index 043d18f..7d3d45d 100644 --- a/examples/dictExample.py +++ b/examples/dictExample.py @@ -5,8 +5,7 @@ #
# Copyright (c) 2003, Paul McGuire
#
-from pyparsing import Literal, Word, Group, Dict, ZeroOrMore, alphas, nums, delimitedList
-import pprint
+import pyparsing as pp
testData = """
+-------+------+------+------+------+------+------+------+------+
@@ -20,22 +19,30 @@ testData = """ """
# define grammar for datatable
-heading = (Literal(
+heading = (pp.Literal(
"+-------+------+------+------+------+------+------+------+------+") +
"| | A1 | B1 | C1 | D1 | A2 | B2 | C2 | D2 |" +
"+=======+======+======+======+======+======+======+======+======+").suppress()
-vert = Literal("|").suppress()
-number = Word(nums)
-rowData = Group( vert + Word(alphas) + vert + delimitedList(number,"|") + vert )
-trailing = Literal(
+vert = pp.Literal("|").suppress()
+number = pp.Word(pp.nums)
+rowData = pp.Group( vert + pp.Word(pp.alphas) + vert + pp.delimitedList(number,"|") + vert )
+trailing = pp.Literal(
"+-------+------+------+------+------+------+------+------+------+").suppress()
-datatable = heading + Dict( ZeroOrMore(rowData) ) + trailing
+datatable = heading + pp.Dict(pp.ZeroOrMore(rowData)) + trailing
# now parse data and print results
data = datatable.parseString(testData)
print(data)
-pprint.pprint(data.asList())
+
+# shortcut for import pprint; pprint.pprint(data.asList())
+data.pprint()
+
+# access all data keys
print("data keys=", list(data.keys()))
+
+# use dict-style access to values
print("data['min']=", data['min'])
+
+# use attribute-style access to values (if key is a valid Python identifier)
print("data.max", data.max)
diff --git a/examples/dictExample2.py b/examples/dictExample2.py index 58162f7..fa1b866 100644 --- a/examples/dictExample2.py +++ b/examples/dictExample2.py @@ -6,7 +6,7 @@ #
# Copyright (c) 2004, Paul McGuire
#
-from pyparsing import Literal, Word, Group, Dict, ZeroOrMore, alphas, nums, delimitedList, pyparsing_common
+from pyparsing import Literal, Word, Group, Dict, ZeroOrMore, alphas, nums, delimitedList, pyparsing_common as ppc
testData = """
+-------+------+------+------+------+------+------+------+------+
@@ -21,7 +21,7 @@ testData = """ # define grammar for datatable
underline = Word("-=")
-number = pyparsing_common.integer
+number = ppc.integer
vert = Literal("|").suppress()
diff --git a/examples/excelExpr.py b/examples/excelExpr.py index 57a3f90..86237ef 100644 --- a/examples/excelExpr.py +++ b/examples/excelExpr.py @@ -7,7 +7,7 @@ from pyparsing import (CaselessKeyword, Suppress, Word, alphas,
alphanums, nums, Optional, Group, oneOf, Forward,
infixNotation, opAssoc, dblQuotedString, delimitedList,
- Combine, Literal, QuotedString, ParserElement, pyparsing_common)
+ Combine, Literal, QuotedString, ParserElement, pyparsing_common as ppc)
ParserElement.enablePackrat()
EQ,LPAR,RPAR,COLON,COMMA = map(Suppress, '=():,')
@@ -26,11 +26,12 @@ expr = Forward() COMPARISON_OP = oneOf("< = > >= <= != <>")
condExpr = expr + COMPARISON_OP + expr
-ifFunc = (CaselessKeyword("if") -
- LPAR +
- Group(condExpr)("condition") +
- COMMA + Group(expr)("if_true") +
- COMMA + Group(expr)("if_false") + RPAR)
+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))
sumFunc = statFunc("sum")
@@ -41,7 +42,7 @@ funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc multOp = oneOf("* /")
addOp = oneOf("+ -")
-numericLiteral = pyparsing_common.number
+numericLiteral = ppc.number
operand = numericLiteral | funcCall | cellRange | cellRef
arithExpr = infixNotation(operand,
[
diff --git a/examples/greetingInGreek.py b/examples/greetingInGreek.py index 8dccd81..8d20c36 100644 --- a/examples/greetingInGreek.py +++ b/examples/greetingInGreek.py @@ -6,10 +6,10 @@ #
# Copyright 2004-2016, by Paul McGuire
#
-from pyparsing import Word, pyparsing_unicode
+from pyparsing import Word, pyparsing_unicode as ppu
# define grammar
-alphas = pyparsing_unicode.Greek.alphas
+alphas = ppu.Greek.alphas
greet = Word(alphas) + ',' + Word(alphas) + '!'
# input string
diff --git a/examples/greetingInKorean.py b/examples/greetingInKorean.py index 7f5a17e..8b6fa49 100644 --- a/examples/greetingInKorean.py +++ b/examples/greetingInKorean.py @@ -6,9 +6,9 @@ #
# Copyright 2004-2016, by Paul McGuire
#
-from pyparsing import Word, pyparsing_unicode
+from pyparsing import Word, pyparsing_unicode as ppu
-koreanChars = pyparsing_unicode.Korean.alphas
+koreanChars = ppu.Korean.alphas
koreanWord = Word(koreanChars, min=2)
# define grammar
diff --git a/examples/holaMundo.py b/examples/holaMundo.py index b24733e..2773a34 100644 --- a/examples/holaMundo.py +++ b/examples/holaMundo.py @@ -3,10 +3,10 @@ # escrito por Marco Alfonso, 2004 Noviembre
# importamos los símbolos requeridos desde el módulo
-from pyparsing import Word, alphas, oneOf, pyparsing_unicode, nums, Group, OneOrMore
+from pyparsing import Word, alphas, oneOf, nums, Group, OneOrMore, pyparsing_unicode as ppu
# usamos las letras en latin1, que incluye las como 'ñ', 'á', 'é', etc.
-alphas = pyparsing_unicode.Latin1.alphas
+alphas = ppu.Latin1.alphas
# Aqui decimos que la gramatica "saludo" DEBE contener
# una palabra compuesta de caracteres alfanumericos
diff --git a/examples/jsonParser.py b/examples/jsonParser.py index 6319c36..fbf76b4 100644 --- a/examples/jsonParser.py +++ b/examples/jsonParser.py @@ -33,29 +33,30 @@ value null
"""
-from pyparsing import *
+import pyparsing as pp
+from pyparsing import pyparsing_common as ppc
def make_keyword(kwd_str, kwd_value):
- return Keyword(kwd_str).setParseAction(replaceWith(kwd_value))
+ return pp.Keyword(kwd_str).setParseAction(pp.replaceWith(kwd_value))
TRUE = make_keyword("true", True)
FALSE = make_keyword("false", False)
NULL = make_keyword("null", None)
-LBRACK, RBRACK, LBRACE, RBRACE, COLON = map(Suppress, "[]{}:")
+LBRACK, RBRACK, LBRACE, RBRACE, COLON = map(pp.Suppress, "[]{}:")
-jsonString = dblQuotedString().setParseAction(removeQuotes)
-jsonNumber = pyparsing_common.number()
+jsonString = pp.dblQuotedString().setParseAction(pp.removeQuotes)
+jsonNumber = ppc.number()
-jsonObject = Forward()
-jsonValue = Forward()
-jsonElements = delimitedList( jsonValue )
-jsonArray = Group(LBRACK + Optional(jsonElements, []) + RBRACK)
-jsonValue << (jsonString | jsonNumber | Group(jsonObject) | jsonArray | TRUE | FALSE | NULL)
-memberDef = Group(jsonString + COLON + jsonValue)
-jsonMembers = delimitedList(memberDef)
-jsonObject << Dict(LBRACE + Optional(jsonMembers) + RBRACE)
+jsonObject = pp.Forward()
+jsonValue = pp.Forward()
+jsonElements = pp.delimitedList( jsonValue )
+jsonArray = pp.Group(LBRACK + pp.Optional(jsonElements, []) + RBRACK)
+jsonValue << (jsonString | jsonNumber | pp.Group(jsonObject) | jsonArray | TRUE | FALSE | NULL)
+memberDef = pp.Group(jsonString + COLON + jsonValue)
+jsonMembers = pp.delimitedList(memberDef)
+jsonObject << pp.Dict(LBRACE + pp.Optional(jsonMembers) + RBRACE)
-jsonComment = cppStyleComment
+jsonComment = pp.cppStyleComment
jsonObject.ignore(jsonComment)
@@ -90,12 +91,11 @@ if __name__ == "__main__": }
"""
- import pprint
results = jsonObject.parseString(testdata)
- pprint.pprint( results.asList() )
+ results.pprint()
print()
def testPrint(x):
- print(type(x),repr(x))
+ print(type(x), repr(x))
print(list(results.glossary.GlossDiv.GlossList.keys()))
testPrint( results.glossary.title )
testPrint( results.glossary.GlossDiv.GlossList.ID )
diff --git a/examples/lucene_grammar.py b/examples/lucene_grammar.py index 6afaad4..07eb319 100644 --- a/examples/lucene_grammar.py +++ b/examples/lucene_grammar.py @@ -7,52 +7,51 @@ # at http://svn.apache.org/viewvc/lucene/dev/trunk/lucene/docs/queryparsersyntax.html
#
-from pyparsing import (Literal, CaselessKeyword, Forward, Regex, QuotedString, Suppress,
- Optional, Group, infixNotation, opAssoc, ParserElement,
- pyparsing_common)
-ParserElement.enablePackrat()
+import pyparsing as pp
+from pyparsing import pyparsing_common as ppc
+pp.ParserElement.enablePackrat()
-COLON,LBRACK,RBRACK,LBRACE,RBRACE,TILDE,CARAT = map(Literal,":[]{}~^")
-LPAR,RPAR = map(Suppress,"()")
-and_, or_, not_, to_ = map(CaselessKeyword, "AND OR NOT TO".split())
+COLON,LBRACK,RBRACK,LBRACE,RBRACE,TILDE,CARAT = map(pp.Literal,":[]{}~^")
+LPAR,RPAR = map(pp.Suppress,"()")
+and_, or_, not_, to_ = map(pp.CaselessKeyword, "AND OR NOT TO".split())
keyword = and_ | or_ | not_ | to_
-expression = Forward()
+expression = pp.Forward()
-valid_word = Regex(r'([a-zA-Z0-9*_+.-]|\\\\|\\([+\-!(){}\[\]^"~*?:]|\|\||&&))+').setName("word")
+valid_word = pp.Regex(r'([a-zA-Z0-9*_+.-]|\\\\|\\([+\-!(){}\[\]^"~*?:]|\|\||&&))+').setName("word")
valid_word.setParseAction(
lambda t : t[0].replace('\\\\',chr(127)).replace('\\','').replace(chr(127),'\\')
)
-string = QuotedString('"')
+string = pp.QuotedString('"')
-required_modifier = Literal("+")("required")
-prohibit_modifier = Literal("-")("prohibit")
-integer = Regex(r"\d+").setParseAction(lambda t:int(t[0]))
-proximity_modifier = Group(TILDE + integer("proximity"))
-number = pyparsing_common.fnumber()
-fuzzy_modifier = TILDE + Optional(number, default=0.5)("fuzzy")
+required_modifier = pp.Literal("+")("required")
+prohibit_modifier = pp.Literal("-")("prohibit")
+integer = ppc.integer()
+proximity_modifier = pp.Group(TILDE + integer("proximity"))
+number = ppc.fnumber()
+fuzzy_modifier = TILDE + pp.Optional(number, default=0.5)("fuzzy")
-term = Forward()
+term = pp.Forward()
field_name = valid_word().setName("fieldname")
-incl_range_search = Group(LBRACK + term("lower") + to_ + term("upper") + RBRACK)
-excl_range_search = Group(LBRACE + term("lower") + to_ + term("upper") + RBRACE)
+incl_range_search = pp.Group(LBRACK + term("lower") + to_ + term("upper") + RBRACK)
+excl_range_search = pp.Group(LBRACE + term("lower") + to_ + term("upper") + RBRACE)
range_search = incl_range_search("incl_range") | excl_range_search("excl_range")
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) +
- (word_expr | string_expr | range_search | Group(LPAR + expression + RPAR)) +
- Optional(boost))
+string_expr = pp.Group(string + proximity_modifier) | string
+word_expr = pp.Group(valid_word + fuzzy_modifier) | valid_word
+term << (pp.Optional(field_name("field") + COLON)
+ + (word_expr | string_expr | range_search | pp.Group(LPAR + expression + RPAR))
+ + pp.Optional(boost))
term.setParseAction(lambda t:[t] if 'field' in t or 'boost' in t else None)
-expression << infixNotation(term,
+expression << pp.infixNotation(term,
[
- (required_modifier | prohibit_modifier, 1, opAssoc.RIGHT),
- ((not_ | '!').setParseAction(lambda: "NOT"), 1, opAssoc.RIGHT),
- ((and_ | '&&').setParseAction(lambda: "AND"), 2, opAssoc.LEFT),
- (Optional(or_ | '||').setParseAction(lambda: "OR"), 2, opAssoc.LEFT),
+ (required_modifier | prohibit_modifier, 1, pp.opAssoc.RIGHT),
+ ((not_ | '!').setParseAction(lambda: "NOT"), 1, pp.opAssoc.RIGHT),
+ ((and_ | '&&').setParseAction(lambda: "AND"), 2, pp.opAssoc.LEFT),
+ (pp.Optional(or_ | '||').setParseAction(lambda: "OR"), 2, pp.opAssoc.LEFT),
])
# test strings taken from grammar description doc, and TestQueryParser.java
diff --git a/examples/simpleSQL.py b/examples/simpleSQL.py index c64a022..57cb251 100644 --- a/examples/simpleSQL.py +++ b/examples/simpleSQL.py @@ -7,7 +7,7 @@ #
from pyparsing import Word, delimitedList, Optional, \
Group, alphas, alphanums, Forward, oneOf, quotedString, \
- ZeroOrMore, restOfLine, CaselessKeyword, pyparsing_common
+ ZeroOrMore, restOfLine, CaselessKeyword, pyparsing_common as ppc
# define SQL tokens
selectStmt = Forward()
@@ -15,18 +15,18 @@ SELECT, FROM, WHERE = map(CaselessKeyword, "select from where".split()) ident = Word( alphas, alphanums + "_$" ).setName("identifier")
columnName = delimitedList(ident, ".", combine=True).setName("column name")
-columnName.addParseAction(pyparsing_common.upcaseTokens)
+columnName.addParseAction(ppc.upcaseTokens)
columnNameList = Group( delimitedList(columnName))
tableName = delimitedList(ident, ".", combine=True).setName("table name")
-tableName.addParseAction(pyparsing_common.upcaseTokens)
+tableName.addParseAction(ppc.upcaseTokens)
tableNameList = Group(delimitedList(tableName))
whereExpression = Forward()
and_, or_, in_ = map(CaselessKeyword, "and or in".split())
binop = oneOf("= != < > >= <= eq ne lt le gt ge", caseless=True)
-realNum = pyparsing_common.real()
-intNum = pyparsing_common.signed_integer()
+realNum = ppc.real()
+intNum = ppc.signed_integer()
columnRval = realNum | intNum | quotedString | columnName # need to add support for alg expressions
whereCondition = Group(
diff --git a/examples/urlExtractor.py b/examples/urlExtractor.py index dc88608..e4299b9 100644 --- a/examples/urlExtractor.py +++ b/examples/urlExtractor.py @@ -1,6 +1,6 @@ # URL extractor
# Copyright 2004, Paul McGuire
-from pyparsing import makeHTMLTags, SkipTo, pyparsing_common
+from pyparsing import makeHTMLTags, SkipTo, pyparsing_common as ppc
import urllib.request
from contextlib import closing
import pprint
@@ -8,7 +8,7 @@ import pprint linkOpenTag, linkCloseTag = makeHTMLTags('a')
linkBody = SkipTo(linkCloseTag)
-linkBody.setParseAction(pyparsing_common.stripHTMLTags)
+linkBody.setParseAction(ppc.stripHTMLTags)
linkBody.addParseAction(lambda toks: ' '.join(toks[0].strip().split()))
link = linkOpenTag + linkBody("body") + linkCloseTag.suppress()
diff --git a/unitTests.py b/unitTests.py index 14cfe22..4786255 100644 --- a/unitTests.py +++ b/unitTests.py @@ -1410,7 +1410,7 @@ class InfixNotationGrammarTest4(ParseTestCase): class InfixNotationGrammarTest5(ParseTestCase): def runTest(self): - from pyparsing import infixNotation, opAssoc, pyparsing_common, Literal, oneOf + from pyparsing import infixNotation, opAssoc, pyparsing_common as ppc, Literal, oneOf expop = Literal('**') signop = oneOf('+ -') @@ -1451,9 +1451,7 @@ class InfixNotationGrammarTest5(ParseTestCase): import operator opn_map = {'+': operator.add, '-': operator.sub} - from pyparsing import pyparsing_common, infixNotation - - operand = pyparsing_common.number().setParseAction(NumberNode) + operand = ppc.number().setParseAction(NumberNode) expr = infixNotation(operand, [ (expop, 2, opAssoc.LEFT, (lambda pr: [pr[0][::-1]], ExpOp)), @@ -1608,6 +1606,7 @@ class UpcaseDowncaseUnicode(ParseTestCase): def runTest(self): import pyparsing as pp + from pyparsing import pyparsing_unicode as ppu import sys if PY_3: unichr = chr @@ -1616,7 +1615,7 @@ class UpcaseDowncaseUnicode(ParseTestCase): a = u'\u00bfC\u00f3mo esta usted?' if not JYTHON_ENV: - ualphas = pp.pyparsing_unicode.alphas + ualphas = ppu.alphas else: ualphas = "".join( unichr(i) for i in list(range(0xd800)) + list(range(0xe000,sys.maxunicode)) if unichr(i).isalpha() ) @@ -3682,11 +3681,12 @@ class ParseResultsNameBelowUngroupedNameTest(ParseTestCase): class ParseResultsNamesInGroupWithDictTest(ParseTestCase): def runTest(self): import pyparsing as pp + from pyparsing import pyparsing_common as ppc - key = pp.pyparsing_common.identifier() - value = pp.pyparsing_common.integer() - lat = pp.pyparsing_common.real() - long = pp.pyparsing_common.real() + key = ppc.identifier() + value = ppc.integer() + lat = ppc.real() + long = ppc.real() EQ = pp.Suppress('=') data = lat("lat") + long("long") + pp.Dict(pp.OneOrMore(pp.Group(key + EQ + value))) @@ -3700,7 +3700,9 @@ class ParseResultsNamesInGroupWithDictTest(ParseTestCase): class FollowedByTest(ParseTestCase): def runTest(self): - expr = pp.Word(pp.alphas)("item") + pp.FollowedBy(pp.pyparsing_common.integer("qty")) + import pyparsing as pp + from pyparsing import pyparsing_common as ppc + expr = pp.Word(pp.alphas)("item") + pp.FollowedBy(ppc.integer("qty")) result = expr.parseString("balloon 99") print_(result.dump()) self.assertTrue('qty' in result, "failed to capture results name in FollowedBy") @@ -3734,25 +3736,26 @@ class SetBreakTest(ParseTestCase): class UnicodeTests(ParseTestCase): def runTest(self): import pyparsing as pp - p_u = pp.pyparsing_unicode + ppu = pp.pyparsing_unicode + ppc = pp.pyparsing_common # verify proper merging of ranges by addition - kanji_printables = p_u.Japanese.Kanji.printables - katakana_printables = p_u.Japanese.Katakana.printables - hiragana_printables = p_u.Japanese.Hiragana.printables - japanese_printables = p_u.Japanese.printables + kanji_printables = ppu.Japanese.Kanji.printables + katakana_printables = ppu.Japanese.Katakana.printables + hiragana_printables = ppu.Japanese.Hiragana.printables + japanese_printables = ppu.Japanese.printables self.assertEqual(set(japanese_printables), set(kanji_printables + katakana_printables + hiragana_printables), "failed to construct ranges by merging Japanese types") # verify proper merging of ranges using multiple inheritance - cjk_printables = p_u.CJK.printables + cjk_printables = ppu.CJK.printables self.assertEqual(len(cjk_printables), len(set(cjk_printables)), "CJK contains duplicate characters - all should be unique") - chinese_printables = p_u.Chinese.printables - korean_printables = p_u.Korean.printables + chinese_printables = ppu.Chinese.printables + korean_printables = ppu.Korean.printables print_(len(cjk_printables), len(set(chinese_printables + korean_printables + japanese_printables))) @@ -3762,7 +3765,7 @@ class UnicodeTests(ParseTestCase): + japanese_printables)), "failed to construct ranges by merging Chinese, Japanese and Korean") - alphas = pp.pyparsing_unicode.Greek.alphas + alphas = ppu.Greek.alphas greet = pp.Word(alphas) + ',' + pp.Word(alphas) + '!' # input string @@ -3773,26 +3776,23 @@ class UnicodeTests(ParseTestCase): "Failed to parse Greek 'Hello, World!' using pyparsing_unicode.Greek.alphas") # define a custom unicode range using multiple inheritance - class Turkish_set(pp.pyparsing_unicode.Latin1, pp.pyparsing_unicode.LatinA): + class Turkish_set(ppu.Latin1, ppu.LatinA): pass self.assertEqual(set(Turkish_set.printables), - set(pp.pyparsing_unicode.Latin1.printables - + pp.pyparsing_unicode.LatinA.printables), + set(ppu.Latin1.printables + ppu.LatinA.printables), "failed to construct ranges by merging Latin1 and LatinA (printables)") self.assertEqual(set(Turkish_set.alphas), - set(pp.pyparsing_unicode.Latin1.alphas - + pp.pyparsing_unicode.LatinA.alphas), + set(ppu.Latin1.alphas + ppu.LatinA.alphas), "failed to construct ranges by merging Latin1 and LatinA (alphas)") self.assertEqual(set(Turkish_set.nums), - set(pp.pyparsing_unicode.Latin1.nums - + pp.pyparsing_unicode.LatinA.nums), + set(ppu.Latin1.nums + ppu.LatinA.nums), "failed to construct ranges by merging Latin1 and LatinA (nums)") key = pp.Word(Turkish_set.alphas) - value = pp.pyparsing_common.integer | pp.Word(Turkish_set.alphas, Turkish_set.alphanums) + value = ppc.integer | pp.Word(Turkish_set.alphas, Turkish_set.alphanums) EQ = pp.Suppress('=') key_value = key + EQ + value @@ -4154,7 +4154,7 @@ class MiscellaneousParserTests(ParseTestCase): def makeTestSuite(): import inspect suite = TestSuite() - suite.addTest( PyparsingTestInit() ) + suite.addTest(PyparsingTestInit()) test_case_classes = ParseTestCase.__subclasses__() # put classes in order as they are listed in the source code @@ -4185,8 +4185,7 @@ def makeTestSuite(): def makeTestSuiteTemp(classes): suite = TestSuite() suite.addTest(PyparsingTestInit()) - for cls in classes: - suite.addTest(cls()) + suite.addTests(cls() for cls in classes) return suite if __name__ == '__main__': |