diff options
author | ptmcg <ptmcg@austin.rr.com> | 2023-04-01 01:49:02 -0500 |
---|---|---|
committer | ptmcg <ptmcg@austin.rr.com> | 2023-04-01 01:49:02 -0500 |
commit | c4cf4a5c1e6c2d2a2dcffe1abae400702efd6426 (patch) | |
tree | 3339c7852d3113359fd66bfb5dd2bc92539ce6f1 /examples | |
parent | 718e858a5d1f1ad371898989da341e3322010edd (diff) | |
download | pyparsing-git-c4cf4a5c1e6c2d2a2dcffe1abae400702efd6426.tar.gz |
Update some examples to latest pyparsing style, PEP8 names
Diffstat (limited to 'examples')
-rw-r--r-- | examples/chemicalFormulas.py | 16 | ||||
-rw-r--r-- | examples/delta_time.py | 96 | ||||
-rw-r--r-- | examples/eval_arith.py | 28 | ||||
-rw-r--r-- | examples/excelExpr.py | 40 | ||||
-rw-r--r-- | examples/gen_ctypes.py | 30 | ||||
-rw-r--r-- | examples/getNTPserversNew.py | 8 | ||||
-rw-r--r-- | examples/greeting.py | 6 | ||||
-rw-r--r-- | examples/greetingInGreek.py | 2 | ||||
-rw-r--r-- | examples/greetingInKorean.py | 2 | ||||
-rw-r--r-- | examples/inv_regex.py | 16 | ||||
-rw-r--r-- | examples/lucene_grammar.py | 18 | ||||
-rw-r--r-- | examples/number_words.py | 34 | ||||
-rw-r--r-- | examples/numerics.py | 10 | ||||
-rw-r--r-- | examples/parsePythonValue.py | 34 | ||||
-rw-r--r-- | examples/pgn.py | 48 | ||||
-rw-r--r-- | examples/protobuf_parser.py | 48 | ||||
-rw-r--r-- | examples/rangeCheck.py | 14 |
17 files changed, 222 insertions, 228 deletions
diff --git a/examples/chemicalFormulas.py b/examples/chemicalFormulas.py index d4c87cd..87a5b6a 100644 --- a/examples/chemicalFormulas.py +++ b/examples/chemicalFormulas.py @@ -23,7 +23,7 @@ element = pp.Word(pp.alphas.upper(), pp.alphas.lower(), max=2).set_name("element # "E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|"
# "M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|"
# "S[bcegimnr]?|T[abcehilm]|U(u[bhopqst])?|V|W|Xe|Yb?|Z[nr]")
-elementRef = pp.Group(element + pp.Optional(pp.Word(digits), default="1"))
+elementRef = pp.Group(element + pp.Opt(pp.Word(digits), default="1"))
formula = elementRef[...]
@@ -46,7 +46,7 @@ print() # Version 2 - access parsed items by results name
elementRef = pp.Group(
- element("symbol") + pp.Optional(pp.Word(digits), default="1")("qty")
+ element("symbol") + pp.Opt(pp.Word(digits), default="1")("qty")
)
formula = elementRef[...]
@@ -69,9 +69,9 @@ formula.runTests( print()
# Version 3 - convert integers during parsing process
-integer = pp.Word(digits).setParseAction(lambda t: int(t[0])).setName("integer")
-elementRef = pp.Group(element("symbol") + pp.Optional(integer, default=1)("qty"))
-formula = elementRef[...].setName("chemical_formula")
+integer = pp.Word(digits).add_parse_action(lambda t: int(t[0])).set_name("integer")
+elementRef = pp.Group(element("symbol") + pp.Opt(integer, default=1)("qty"))
+formula = elementRef[...].set_name("chemical_formula")
def sum_atomic_weights_by_results_name_with_converted_ints(element_list):
@@ -103,10 +103,10 @@ def cvt_subscript_int(s): return ret
-subscript_int = pp.Word(subscript_digits).addParseAction(cvt_subscript_int).set_name("subscript")
+subscript_int = pp.Word(subscript_digits).add_parse_action(cvt_subscript_int).set_name("subscript")
-elementRef = pp.Group(element("symbol") + pp.Optional(subscript_int, default=1)("qty"))
-formula = elementRef[1, ...].setName("chemical_formula")
+elementRef = pp.Group(element("symbol") + pp.Opt(subscript_int, default=1)("qty"))
+formula = elementRef[1, ...].set_name("chemical_formula")
formula.runTests(
"""\
H₂O
diff --git a/examples/delta_time.py b/examples/delta_time.py index 93ae8f8..28c03af 100644 --- a/examples/delta_time.py +++ b/examples/delta_time.py @@ -39,7 +39,7 @@ __all__ = ["time_expression"] # basic grammar definitions def make_integer_word_expr(int_name, int_value): - return pp.CaselessKeyword(int_name).addParseAction(pp.replaceWith(int_value)) + return pp.CaselessKeyword(int_name).add_parse_action(pp.replaceWith(int_value)) integer_word = pp.MatchFirst( @@ -50,52 +50,52 @@ integer_word = pp.MatchFirst( " seventeen eighteen nineteen twenty".split(), start=1, ) -).setName("integer_word") +).set_name("integer_word") integer = pp.pyparsing_common.integer | integer_word -integer.setName("numeric") +integer.set_name("numeric") CK = pp.CaselessKeyword CL = pp.CaselessLiteral -today, tomorrow, yesterday, noon, midnight, now = map( - CK, "today tomorrow yesterday noon midnight now".split() +today, tomorrow, yesterday, noon, midnight, now = CK.using_each( + "today tomorrow yesterday noon midnight now".split() ) def plural(s): - return CK(s) | CK(s + "s").addParseAction(pp.replaceWith(s)) + return CK(s) | CK(s + "s").add_parse_action(pp.replaceWith(s)) week, day, hour, minute, second = map(plural, "week day hour minute second".split()) time_units = hour | minute | second -any_time_units = (week | day | time_units).setName("time_units") +any_time_units = (week | day | time_units).set_name("time_units") am = CL("am") pm = CL("pm") COLON = pp.Suppress(":") -in_ = CK("in").setParseAction(pp.replaceWith(1)) -from_ = CK("from").setParseAction(pp.replaceWith(1)) -before = CK("before").setParseAction(pp.replaceWith(-1)) -after = CK("after").setParseAction(pp.replaceWith(1)) -ago = CK("ago").setParseAction(pp.replaceWith(-1)) -next_ = CK("next").setParseAction(pp.replaceWith(1)) -last_ = CK("last").setParseAction(pp.replaceWith(-1)) +in_ = CK("in").set_parse_action(pp.replaceWith(1)) +from_ = CK("from").set_parse_action(pp.replaceWith(1)) +before = CK("before").set_parse_action(pp.replaceWith(-1)) +after = CK("after").set_parse_action(pp.replaceWith(1)) +ago = CK("ago").set_parse_action(pp.replaceWith(-1)) +next_ = CK("next").set_parse_action(pp.replaceWith(1)) +last_ = CK("last").set_parse_action(pp.replaceWith(-1)) at_ = CK("at") on_ = CK("on") couple = ( - (pp.Optional(CK("a")) + CK("couple") + pp.Optional(CK("of"))) - .setParseAction(pp.replaceWith(2)) - .setName("couple") + (pp.Opt(CK("a")) + CK("couple") + pp.Opt(CK("of"))) + .set_parse_action(pp.replaceWith(2)) + .set_name("couple") ) -a_qty = (CK("a") | CK("an")).setParseAction(pp.replaceWith(1)) -the_qty = CK("the").setParseAction(pp.replaceWith(1)) +a_qty = (CK("a") | CK("an")).set_parse_action(pp.replaceWith(1)) +the_qty = CK("the").set_parse_action(pp.replaceWith(1)) qty = pp.ungroup( - (integer | couple | a_qty | the_qty).setName("qty_expression") -).setName("qty") -time_ref_present = pp.Empty().addParseAction(pp.replaceWith(True))("time_ref_present") + (integer | couple | a_qty | the_qty).set_name("qty_expression") +).set_name("qty") +time_ref_present = pp.Empty().add_parse_action(pp.replace_with(True))("time_ref_present") def fill_24hr_time_fields(t): @@ -112,25 +112,25 @@ def fill_default_time_fields(t): weekday_name_list = list(calendar.day_name) -weekday_name = pp.oneOf(weekday_name_list).setName("weekday_name") +weekday_name = pp.one_of(weekday_name_list).set_name("weekday_name") -_24hour_time = ~(integer + any_time_units).setName("numbered_time_units") + pp.Word(pp.nums, exact=4).setName("HHMM").addParseAction( +_24hour_time = ~(integer + any_time_units).set_name("numbered_time_units") + pp.Word(pp.nums, exact=4).set_name("HHMM").add_parse_action( lambda t: [int(t[0][:2]), int(t[0][2:])], fill_24hr_time_fields ) -_24hour_time.setName("0000 time") +_24hour_time.set_name("0000 time") ampm = am | pm timespec = ( integer("HH") - + pp.Optional( - CK("o'clock") | COLON + integer("MM") + pp.Optional(COLON + integer("SS")) + + pp.Opt( + CK("o'clock") | COLON + integer("MM") + pp.Opt(COLON + integer("SS")) ) + (am | pm)("ampm") -).addParseAction(fill_default_time_fields) +).add_parse_action(fill_default_time_fields) absolute_time = _24hour_time | timespec -absolute_time.setName("absolute time") +absolute_time.set_name("absolute time") absolute_time_of_day = noon | midnight | now | absolute_time -absolute_time_of_day.setName("time of day") +absolute_time_of_day.set_name("time of day") def add_computed_time(t): @@ -145,12 +145,12 @@ def add_computed_time(t): t["computed_time"] = time(hour=t.HH, minute=t.MM, second=t.SS) -absolute_time_of_day.addParseAction(add_computed_time) +absolute_time_of_day.add_parse_action(add_computed_time) # relative_time_reference ::= qty time_units ('ago' | ('from' | 'before' | 'after') absolute_time_of_day) # | 'in' qty time_units -time_units = (hour | minute | second).setName("time unit") +time_units = (hour | minute | second).set_name("time unit") relative_time_reference = ( ( qty("qty") @@ -162,7 +162,7 @@ relative_time_reference = ( ) ) | in_("dir") + qty("qty") + time_units("units") -).setName("relative time") +).set_name("relative time") def compute_relative_time(t): @@ -174,10 +174,10 @@ def compute_relative_time(t): t["time_delta"] = timedelta(seconds=t.dir * delta_seconds) -relative_time_reference.addParseAction(compute_relative_time) +relative_time_reference.add_parse_action(compute_relative_time) time_reference = absolute_time_of_day | relative_time_reference -time_reference.setName("time reference") +time_reference.set_name("time reference") def add_default_time_ref_fields(t): @@ -185,13 +185,13 @@ def add_default_time_ref_fields(t): t["time_delta"] = timedelta() -time_reference.addParseAction(add_default_time_ref_fields) +time_reference.add_parse_action(add_default_time_ref_fields) # absolute_day_reference ::= 'today' | 'tomorrow' | 'yesterday' | ('next' | 'last') weekday_name # day_units ::= 'days' | 'weeks' day_units = day | week -weekday_reference = pp.Optional(next_ | last_, 1)("dir") + weekday_name("day_name") +weekday_reference = pp.Opt(next_ | last_, 1)("dir") + weekday_name("day_name") def convert_abs_day_reference_to_date(t): @@ -222,8 +222,8 @@ def convert_abs_day_reference_to_date(t): absolute_day_reference = ( today | tomorrow | yesterday | now + time_ref_present | weekday_reference ) -absolute_day_reference.addParseAction(convert_abs_day_reference_to_date) -absolute_day_reference.setName("absolute day") +absolute_day_reference.add_parse_action(convert_abs_day_reference_to_date) +absolute_day_reference.set_name("absolute day") # relative_day_reference ::= 'in' qty day_units # | qty day_units @@ -234,7 +234,7 @@ relative_day_reference = in_("dir") + qty("qty") + day_units("units") | qty( ) + day_units("units") + ( ago("dir") | ((from_ | before | after)("dir") + absolute_day_reference("ref_day")) ) -relative_day_reference.setName("relative day") +relative_day_reference.set_name("relative day") def compute_relative_date(t): @@ -247,11 +247,11 @@ def compute_relative_date(t): t["date_delta"] = timedelta(days=day_diff) -relative_day_reference.addParseAction(compute_relative_date) +relative_day_reference.add_parse_action(compute_relative_date) # combine expressions for absolute and relative day references day_reference = relative_day_reference | absolute_day_reference -day_reference.setName("day reference") +day_reference.set_name("day reference") def add_default_date_fields(t): @@ -259,13 +259,13 @@ def add_default_date_fields(t): t["date_delta"] = timedelta() -day_reference.addParseAction(add_default_date_fields) +day_reference.add_parse_action(add_default_date_fields) # combine date and time expressions into single overall parser -time_and_day = time_reference + time_ref_present + pp.Optional( - pp.Optional(on_) + day_reference -) | day_reference + pp.Optional(at_ + absolute_time_of_day + time_ref_present) -time_and_day.setName("time and day") +time_and_day = time_reference + time_ref_present + pp.Opt( + pp.Opt(on_) + day_reference +) | day_reference + pp.Opt(at_ + absolute_time_of_day + time_ref_present) +time_and_day.set_name("time and day") # parse actions for total time_and_day expression def save_original_string(s, l, t): @@ -318,7 +318,7 @@ def remove_temp_keys(t): del t[k] -time_and_day.addParseAction(save_original_string, compute_timestamp, remove_temp_keys) +time_and_day.add_parse_action(save_original_string, compute_timestamp, remove_temp_keys) time_expression = time_and_day diff --git a/examples/eval_arith.py b/examples/eval_arith.py index 613e728..3a19ae0 100644 --- a/examples/eval_arith.py +++ b/examples/eval_arith.py @@ -13,9 +13,9 @@ from pyparsing import ( nums, alphas, Combine, - oneOf, - opAssoc, - infixNotation, + one_of, + OpAssoc, + infix_notation, Literal, ParserElement, ) @@ -143,28 +143,28 @@ real = Combine(Word(nums) + "." + Word(nums)) variable = Word(alphas, exact=1) operand = real | integer | variable -signop = oneOf("+ -") -multop = oneOf("* /") -plusop = oneOf("+ -") +signop = one_of("+ -") +multop = one_of("* /") +plusop = one_of("+ -") expop = Literal("**") # use parse actions to attach EvalXXX constructors to sub-expressions operand.setParseAction(EvalConstant) -arith_expr = infixNotation( +arith_expr = infix_notation( operand, [ - (signop, 1, opAssoc.RIGHT, EvalSignOp), - (expop, 2, opAssoc.LEFT, EvalPowerOp), - (multop, 2, opAssoc.LEFT, EvalMultOp), - (plusop, 2, opAssoc.LEFT, EvalAddOp), + (signop, 1, OpAssoc.RIGHT, EvalSignOp), + (expop, 2, OpAssoc.LEFT, EvalPowerOp), + (multop, 2, OpAssoc.LEFT, EvalMultOp), + (plusop, 2, OpAssoc.LEFT, EvalAddOp), ], ) -comparisonop = oneOf("< <= > >= != = <> LT GT LE GE EQ NE") -comp_expr = infixNotation( +comparisonop = one_of("< <= > >= != = <> LT GT LE GE EQ NE") +comp_expr = infix_notation( arith_expr, [ - (comparisonop, 2, opAssoc.LEFT, EvalComparisonOp), + (comparisonop, 2, OpAssoc.LEFT, EvalComparisonOp), ], ) diff --git a/examples/excelExpr.py b/examples/excelExpr.py index 966e38b..87af4fb 100644 --- a/examples/excelExpr.py +++ b/examples/excelExpr.py @@ -11,14 +11,14 @@ from pyparsing import ( alphas,
alphanums,
nums,
- Optional,
+ Opt,
Group,
- oneOf,
+ one_of,
Forward,
- infixNotation,
- opAssoc,
+ infix_notation,
+ OpAssoc,
dblQuotedString,
- delimitedList,
+ DelimitedList,
Combine,
Literal,
QuotedString,
@@ -28,13 +28,13 @@ from pyparsing import ( ParserElement.enablePackrat()
-EQ, LPAR, RPAR, COLON, COMMA = map(Suppress, "=():,")
-EXCL, DOLLAR = map(Literal, "!$")
+EQ, LPAR, RPAR, COLON, COMMA = Suppress.using_each("=():,")
+EXCL, DOLLAR = Literal.using_each("!$")
sheetRef = Word(alphas, alphanums) | QuotedString("'", escQuote="''")
-colRef = Optional(DOLLAR) + Word(alphas, max=2)
-rowRef = Optional(DOLLAR) + Word(nums)
+colRef = Opt(DOLLAR) + Word(alphas, max=2)
+rowRef = Opt(DOLLAR) + Word(nums)
cellRef = Combine(
- Group(Optional(sheetRef + EXCL)("sheet") + colRef("col") + rowRef("row"))
+ Group(Opt(sheetRef + EXCL)("sheet") + colRef("col") + rowRef("row"))
)
cellRange = (
@@ -45,7 +45,7 @@ cellRange = ( expr = Forward()
-COMPARISON_OP = oneOf("< = > >= <= != <>")
+COMPARISON_OP = one_of("< = > >= <= != <>")
condExpr = expr + COMPARISON_OP + expr
ifFunc = (
@@ -61,7 +61,7 @@ ifFunc = ( def stat_function(name):
- return Group(CaselessKeyword(name) + Group(LPAR + delimitedList(expr) + RPAR))
+ return Group(CaselessKeyword(name) + Group(LPAR + DelimitedList(expr) + RPAR))
sumFunc = stat_function("sum")
@@ -70,23 +70,23 @@ maxFunc = stat_function("max") aveFunc = stat_function("ave")
funcCall = ifFunc | sumFunc | minFunc | maxFunc | aveFunc
-multOp = oneOf("* /")
-addOp = oneOf("+ -")
+multOp = one_of("* /")
+addOp = one_of("+ -")
numericLiteral = ppc.number
operand = numericLiteral | funcCall | cellRange | cellRef
-arithExpr = infixNotation(
+arithExpr = infix_notation(
operand,
[
- (multOp, 2, opAssoc.LEFT),
- (addOp, 2, opAssoc.LEFT),
+ (multOp, 2, OpAssoc.LEFT),
+ (addOp, 2, OpAssoc.LEFT),
],
)
textOperand = dblQuotedString | cellRef
-textExpr = infixNotation(
+textExpr = infix_notation(
textOperand,
[
- ("&", 2, opAssoc.LEFT),
+ ("&", 2, OpAssoc.LEFT),
],
)
@@ -94,7 +94,7 @@ expr <<= arithExpr | textExpr def main():
- success, report = (EQ + expr).runTests(
+ success, report = (EQ + expr).run_tests(
"""\
=3*A7+5
=3*Sheet1!$A$7+5
diff --git a/examples/gen_ctypes.py b/examples/gen_ctypes.py index 176644f..0eb0b7b 100644 --- a/examples/gen_ctypes.py +++ b/examples/gen_ctypes.py @@ -44,16 +44,16 @@ typemap = { "void": "None",
}
-LPAR, RPAR, LBRACE, RBRACE, COMMA, SEMI = map(Suppress, "(){},;")
-ident = Word(alphas, alphanums + "_")
+LPAR, RPAR, LBRACE, RBRACE, COMMA, SEMI = Suppress.using_each("(){},;")
+ident = pyparsing_common.identifier
integer = Regex(r"[+-]?\d+")
hexinteger = Regex(r"0x[0-9a-fA-F]+")
const = Suppress("const")
-primitiveType = oneOf(t for t in typemap if not t.endswith("*"))
+primitiveType = one_of(t for t in typemap if not t.endswith("*"))
structType = Suppress("struct") + ident
vartype = (
- Optional(const) + (primitiveType | structType | ident) + Optional(Word("*")("ptr"))
+ Opt(const) + (primitiveType | structType | ident) + Opt(Word("*")("ptr"))
)
@@ -64,14 +64,14 @@ def normalizetype(t): # ~ return ret
-vartype.setParseAction(normalizetype)
+vartype.set_parse_action(normalizetype)
-arg = Group(vartype("argtype") + Optional(ident("argname")))
+arg = Group(vartype("argtype") + Opt(ident("argname")))
func_def = (
vartype("fn_type")
+ ident("fn_name")
+ LPAR
- + Optional(delimitedList(arg | "..."))("fn_args")
+ + Opt(DelimitedList(arg | "..."))("fn_args")
+ RPAR
+ SEMI
)
@@ -82,7 +82,7 @@ def derivefields(t): t["varargs"] = True
-func_def.setParseAction(derivefields)
+func_def.set_parse_action(derivefields)
fn_typedef = "typedef" + func_def
var_typedef = "typedef" + primitiveType("primType") + ident("name") + SEMI
@@ -90,10 +90,10 @@ var_typedef = "typedef" + primitiveType("primType") + ident("name") + SEMI enum_def = (
Keyword("enum")
+ LBRACE
- + delimitedList(Group(ident("name") + "=" + (hexinteger | integer)("value")))(
+ + DelimitedList(Group(ident("name") + "=" + (hexinteger | integer)("value")))(
"evalues"
)
- + Optional(COMMA)
+ + Opt(COMMA)
+ RBRACE
)
@@ -135,13 +135,13 @@ def typeAsCtypes(typestr): # scan input header text for primitive typedefs
-for td, _, _ in var_typedef.scanString(c_header):
+for td, _, _ in var_typedef.scan_string(c_header):
typedefs.append((td.name, td.primType))
# add typedef type to typemap to map to itself
typemap[td.name] = td.name
# scan input header text for function typedefs
-fn_typedefs = fn_typedef.searchString(c_header)
+fn_typedefs = fn_typedef.search_string(c_header)
# add each function typedef to typemap to map to itself
for fntd in fn_typedefs:
typemap[fntd.fn_name] = fntd.fn_name
@@ -149,7 +149,7 @@ for fntd in fn_typedefs: # scan input header text, and keep running list of user-defined types
for fn, _, _ in (
cStyleComment.suppress() | fn_typedef.suppress() | func_def
-).scanString(c_header):
+).scan_string(c_header):
if not fn:
continue
getUDType(fn.fn_type)
@@ -160,8 +160,8 @@ for fn, _, _ in ( functions.append(fn)
# scan input header text for enums
-enum_def.ignore(cppStyleComment)
-for en_, _, _ in enum_def.scanString(c_header):
+enum_def.ignore(cpp_style_comment)
+for en_, _, _ in enum_def.scan_string(c_header):
for ev in en_.evalues:
enum_constants.append((ev.name, ev.value))
diff --git a/examples/getNTPserversNew.py b/examples/getNTPserversNew.py index 5fcd9d1..8c4c94f 100644 --- a/examples/getNTPserversNew.py +++ b/examples/getNTPserversNew.py @@ -13,8 +13,8 @@ from urllib.request import urlopen integer = pp.Word(pp.nums) ipAddress = ppc.ipv4_address() -hostname = pp.delimitedList(pp.Word(pp.alphas, pp.alphanums + "-_"), ".", combine=True) -tdStart, tdEnd = pp.makeHTMLTags("td") +hostname = pp.DelimitedList(pp.Word(pp.alphas, pp.alphanums + "-_"), ".", combine=True) +tdStart, tdEnd = pp.make_html_tags("td") timeServerPattern = ( tdStart + hostname("hostname") @@ -33,6 +33,6 @@ with urlopen(nistTimeServerURL) as serverListPage: serverListHTML = serverListPage.read().decode("UTF-8") addrs = {} -for srvr, startloc, endloc in timeServerPattern.scanString(serverListHTML): - print("{} ({}) - {}".format(srvr.ipAddr, srvr.hostname.strip(), srvr.loc.strip())) +for srvr, startloc, endloc in timeServerPattern.scan_string(serverListHTML): + print(f"{srvr.ipAddr} ({srvr.hostname.strip()}) - {srvr.loc.strip()}") addrs[srvr.ipAddr] = srvr.loc diff --git a/examples/greeting.py b/examples/greeting.py index 28a534a..17a7b2a 100644 --- a/examples/greeting.py +++ b/examples/greeting.py @@ -8,16 +8,16 @@ import pyparsing as pp # define grammar -greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.oneOf("! ? .") +greet = pp.Word(pp.alphas) + "," + pp.Word(pp.alphas) + pp.one_of("! ? .") # input string hello = "Hello, World!" # parse input string -print(hello, "->", greet.parseString(hello)) +print(hello, "->", greet.parse_string(hello)) # parse a bunch of input strings -greet.runTests( +greet.run_tests( """\ Hello, World! Ahoy, Matey! diff --git a/examples/greetingInGreek.py b/examples/greetingInGreek.py index ed98e9a..aa8272a 100644 --- a/examples/greetingInGreek.py +++ b/examples/greetingInGreek.py @@ -15,4 +15,4 @@ greet = Word(alphas) + "," + Word(alphas) + "!" hello = "Καλημέρα, κόσμε!"
# parse input string
-print(greet.parseString(hello))
+print(greet.parse_string(hello))
diff --git a/examples/greetingInKorean.py b/examples/greetingInKorean.py index 00ea9bc..63afebd 100644 --- a/examples/greetingInKorean.py +++ b/examples/greetingInKorean.py @@ -17,4 +17,4 @@ greet = koreanWord + "," + koreanWord + "!" hello = "안녕, 여러분!" # "Hello, World!" in Korean
# parse input string
-print(greet.parseString(hello))
+print(greet.parse_string(hello))
diff --git a/examples/inv_regex.py b/examples/inv_regex.py index d22d098..8a0c1bb 100644 --- a/examples/inv_regex.py +++ b/examples/inv_regex.py @@ -192,12 +192,12 @@ _parser = None def parser():
global _parser
if _parser is None:
- ParserElement.setDefaultWhitespaceChars("")
- lbrack, rbrack, lbrace, rbrace, lparen, rparen, colon, qmark = map(
- Literal, "[]{}():?"
+ ParserElement.set_default_whitespace_chars("")
+ lbrack, rbrack, lbrace, rbrace, lparen, rparen, colon, qmark = Literal.using_each(
+ "[]{}():?"
)
- re_macro = Combine("\\" + one_of(list("dws")))
+ re_macro = Combine("\\" + one_of("d w s"))
escaped_char = ~re_macro + Combine("\\" + one_of(list(printables)))
re_literal_char = (
"".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"
@@ -213,10 +213,10 @@ def parser(): | one_of(list("*+?"))
)
- re_range.setParseAction(handle_range)
- re_literal.setParseAction(handle_literal)
- re_macro.setParseAction(handle_macro)
- re_dot.setParseAction(handle_dot)
+ re_range.add_parse_action(handle_range)
+ re_literal.add_parse_action(handle_literal)
+ re_macro.add_parse_action(handle_macro)
+ re_dot.add_parse_action(handle_dot)
re_term = re_literal | re_range | re_macro | re_dot | re_non_capture_group
re_expr = infix_notation(
diff --git a/examples/lucene_grammar.py b/examples/lucene_grammar.py index 437c5e3..613f29e 100644 --- a/examples/lucene_grammar.py +++ b/examples/lucene_grammar.py @@ -11,7 +11,7 @@ import pyparsing as pp from pyparsing import pyparsing_common as ppc -pp.ParserElement.enablePackrat() +pp.ParserElement.enable_packrat() COLON, LBRACK, RBRACK, LBRACE, RBRACE, TILDE, CARAT = pp.Literal.using_each(":[]{}~^") LPAR, RPAR = pp.Suppress.using_each("()") @@ -35,7 +35,7 @@ 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") +fuzzy_modifier = TILDE + pp.Opt(number, default=0.5)("fuzzy") term = pp.Forward().set_name("field") field_name = valid_word().set_name("fieldname") @@ -48,22 +48,22 @@ string_expr = pp.Group(string + proximity_modifier) | string word_expr = pp.Group(valid_word + fuzzy_modifier) | valid_word term <<= ( ~keyword - + pp.Optional(field_name("field") + COLON) + + pp.Opt(field_name("field") + COLON) + (word_expr | string_expr | range_search | pp.Group(LPAR + expression + RPAR)) - + pp.Optional(boost) + + pp.Opt(boost) ) term.set_parse_action(lambda t: [t] if "field" in t or "boost" in t else None) expression <<= pp.infixNotation( term, [ - (required_modifier | prohibit_modifier, 1, pp.opAssoc.RIGHT), - ((not_ | "!").set_parse_action(lambda: "NOT"), 1, pp.opAssoc.RIGHT), - ((and_ | "&&").set_parse_action(lambda: "AND"), 2, pp.opAssoc.LEFT), + (required_modifier | prohibit_modifier, 1, pp.OpAssoc.RIGHT), + ((not_ | "!").set_parse_action(lambda: "NOT"), 1, pp.OpAssoc.RIGHT), + ((and_ | "&&").set_parse_action(lambda: "AND"), 2, pp.OpAssoc.LEFT), ( - pp.Optional(or_ | "||").setName("or").set_parse_action(lambda: "OR"), + pp.Opt(or_ | "||").setName("or").set_parse_action(lambda: "OR"), 2, - pp.opAssoc.LEFT, + pp.OpAssoc.LEFT, ), ], ).set_name("query expression") diff --git a/examples/number_words.py b/examples/number_words.py index f4e282e..181740f 100644 --- a/examples/number_words.py +++ b/examples/number_words.py @@ -52,9 +52,9 @@ def define_numeric_word_range( ) if len(names) == 1: - ret.setName(names[0]) + ret.set_name(names[0]) else: - ret.setName("{}-{}".format(names[0], names[-1])) + ret.set_name(f"{names[0]}-{names[-1]}") return ret @@ -66,8 +66,8 @@ def multiply(t): return mul(*t) -opt_dash = pp.Optional(pp.Suppress("-")).setName("'-'") -opt_and = pp.Optional((pp.CaselessKeyword("and") | "-").suppress()).setName("'and/-'") +opt_dash = pp.Opt(pp.Suppress("-")).set_name("'-'") +opt_and = pp.Opt((pp.CaselessKeyword("and") | "-").suppress()).set_name("'and/-'") units = define_numeric_word_range("one two three four five six seven eight nine", 1, 9) teens_only = define_numeric_word_range( @@ -81,38 +81,38 @@ teens = ten | teens_only tens = define_numeric_word_range( "twenty thirty forty fifty sixty seventy eighty ninety", 20, 90, 10 ) -one_to_99 = (units | teens | (tens + pp.Optional(opt_dash + units))).setName("1-99") -one_to_99.addParseAction(sum) +one_to_99 = (units | teens | (tens + pp.Opt(opt_dash + units))).set_name("1-99") +one_to_99.add_parse_action(sum) hundred = define_numeric_word_range("hundred", 100) thousand = define_numeric_word_range("thousand", 1000) hundreds = (units | teens_only | (tens + opt_dash + units)) + hundred -hundreds.setName("100s") +hundreds.set_name("100s") one_to_999 = ( - (pp.Optional(hundreds + opt_and) + one_to_99 | hundreds).addParseAction(sum) -).setName("1-999") + (pp.Opt(hundreds + opt_and) + one_to_99 | hundreds).add_parse_action(sum) +).set_name("1-999") thousands = one_to_999 + thousand -thousands.setName("1000s") +thousands.set_name("1000s") # for hundreds and thousands, must scale up (multiply) accordingly -hundreds.addParseAction(multiply) -thousands.addParseAction(multiply) +hundreds.add_parse_action(multiply) +thousands.add_parse_action(multiply) numeric_expression = ( - pp.Optional(thousands + opt_and) + pp.Optional(hundreds + opt_and) + one_to_99 - | pp.Optional(thousands + opt_and) + hundreds + pp.Opt(thousands + opt_and) + pp.Opt(hundreds + opt_and) + one_to_99 + | pp.Opt(thousands + opt_and) + hundreds | thousands -).setName("numeric_words") +).set_name("numeric_words") # sum all sub-results into total -numeric_expression.addParseAction(sum) +numeric_expression.add_parse_action(sum) if __name__ == "__main__": - numeric_expression.runTests( + numeric_expression.run_tests( """ one seven diff --git a/examples/numerics.py b/examples/numerics.py index 3a1f9e9..f29c508 100644 --- a/examples/numerics.py +++ b/examples/numerics.py @@ -49,18 +49,18 @@ tests = """\ from pyparsing import Regex
comma_decimal = Regex(r"\d{1,2}(([ .])\d\d\d(\2\d\d\d)*)?,\d*")
-comma_decimal.setParseAction(
+comma_decimal.add_parse_action(
lambda t: float(t[0].replace(" ", "").replace(".", "").replace(",", "."))
)
dot_decimal = Regex(r"\d{1,2}(([ ,])\d\d\d(\2\d\d\d)*)?\.\d*")
-dot_decimal.setParseAction(lambda t: float(t[0].replace(" ", "").replace(",", "")))
+dot_decimal.add_parse_action(lambda t: float(t[0].replace(" ", "").replace(",", "")))
decimal = comma_decimal ^ dot_decimal
-decimal.runTests(tests, parseAll=True)
+decimal.run_tests(tests, parse_all=True)
grouped_integer = Regex(r"\d{1,2}(([ .,])\d\d\d(\2\d\d\d)*)?")
-grouped_integer.setParseAction(
+grouped_integer.add_parse_action(
lambda t: int(t[0].replace(" ", "").replace(",", "").replace(".", ""))
)
-grouped_integer.runTests(tests, parseAll=False)
+grouped_integer.run_tests(tests, parse_all=False)
diff --git a/examples/parsePythonValue.py b/examples/parsePythonValue.py index 75afdfd..fd039ef 100644 --- a/examples/parsePythonValue.py +++ b/examples/parsePythonValue.py @@ -8,25 +8,23 @@ import pyparsing as pp cvtBool = lambda t: t[0] == "True" cvtInt = lambda toks: int(toks[0]) cvtReal = lambda toks: float(toks[0]) -cvtTuple = lambda toks: tuple(toks.asList()) -cvtDict = lambda toks: dict(toks.asList()) -cvtList = lambda toks: [toks.asList()] +cvtTuple = lambda toks: tuple(toks.as_list()) +cvtDict = lambda toks: dict(toks.as_list()) +cvtList = lambda toks: [toks.as_list()] # define punctuation as suppressed literals -lparen, rparen, lbrack, rbrack, lbrace, rbrace, colon, comma = map( - pp.Suppress, "()[]{}:," -) +lparen, rparen, lbrack, rbrack, lbrace, rbrace, colon, comma = pp.Suppress.using_each("()[]{}:,") -integer = pp.Regex(r"[+-]?\d+").setName("integer").setParseAction(cvtInt) -real = pp.Regex(r"[+-]?\d+\.\d*([Ee][+-]?\d+)?").setName("real").setParseAction(cvtReal) +integer = pp.Regex(r"[+-]?\d+").set_name("integer").add_parse_action(cvtInt) +real = pp.Regex(r"[+-]?\d+\.\d*([Ee][+-]?\d+)?").set_name("real").add_parse_action(cvtReal) tupleStr = pp.Forward().set_name("tuple_expr") listStr = pp.Forward().set_name("list_expr") dictStr = pp.Forward().set_name("dict_expr") -unistr = pp.unicodeString().setParseAction(lambda t: t[0][2:-1]) -quoted_str = pp.quotedString().setParseAction(lambda t: t[0][1:-1]) -boolLiteral = pp.oneOf("True False", asKeyword=True).setParseAction(cvtBool) -noneLiteral = pp.Keyword("None").setParseAction(pp.replaceWith(None)) +unistr = pp.unicodeString().add_parse_action(lambda t: t[0][2:-1]) +quoted_str = pp.quotedString().add_parse_action(lambda t: t[0][1:-1]) +boolLiteral = pp.oneOf("True False", as_keyword=True).add_parse_action(cvtBool) +noneLiteral = pp.Keyword("None").add_parse_action(pp.replace_with(None)) listItem = ( real @@ -41,20 +39,20 @@ listItem = ( ).set_name("list_item") tupleStr <<= ( - lparen + pp.Optional(pp.delimitedList(listItem, allow_trailing_delim=True)) + rparen + lparen + pp.Opt(pp.DelimitedList(listItem, allow_trailing_delim=True)) + rparen ) -tupleStr.setParseAction(cvtTuple) +tupleStr.add_parse_action(cvtTuple) listStr <<= ( - lbrack + pp.Optional(pp.delimitedList(listItem, allow_trailing_delim=True)) + rbrack + lbrack + pp.Opt(pp.DelimitedList(listItem, allow_trailing_delim=True)) + rbrack ) -listStr.setParseAction(cvtList, lambda t: t[0]) +listStr.add_parse_action(cvtList, lambda t: t[0]) dictEntry = pp.Group(listItem + colon + listItem).set_name("dict_entry") dictStr <<= ( - lbrace + pp.Optional(pp.delimitedList(dictEntry, allow_trailing_delim=True)) + rbrace + lbrace + pp.Opt(pp.DelimitedList(dictEntry, allow_trailing_delim=True)) + rbrace ) -dictStr.setParseAction(cvtDict) +dictStr.add_parse_action(cvtDict) if __name__ == "__main__": diff --git a/examples/pgn.py b/examples/pgn.py index d9889d6..34f0ef8 100644 --- a/examples/pgn.py +++ b/examples/pgn.py @@ -15,11 +15,9 @@ from pyparsing import ( Forward,
Group,
Literal,
- oneOf,
- OneOrMore,
- Optional,
+ one_of,
+ Opt,
Suppress,
- ZeroOrMore,
Word,
)
from pyparsing import ParseException
@@ -28,19 +26,19 @@ from pyparsing import ParseException # define pgn grammar
#
-tag = Suppress("[") + Word(alphanums) + Combine(quotedString) + Suppress("]")
+tag = Suppress("[") + Word(alphanums) + quotedString + Suppress("]")
comment = Suppress("{") + Word(alphanums + " ") + Suppress("}")
dot = Literal(".")
-piece = oneOf("K Q B N R")
-file_coord = oneOf("a b c d e f g h")
-rank_coord = oneOf("1 2 3 4 5 6 7 8")
-capture = oneOf("x :")
+piece = one_of("K Q B N R")
+file_coord = one_of("a b c d e f g h")
+rank_coord = one_of("1 2 3 4 5 6 7 8")
+capture = one_of("x :")
promote = Literal("=")
-castle_queenside = oneOf("O-O-O 0-0-0 o-o-o")
-castle_kingside = oneOf("O-O 0-0 o-o")
+castle_queenside = one_of("O-O-O 0-0-0 o-o-o")
+castle_kingside = one_of("O-O 0-0 o-o")
-move_number = Optional(comment) + Word(nums) + dot
+move_number = Opt(comment) + Word(nums) + dot
m1 = file_coord + rank_coord # pawn move e.g. d4
m2 = file_coord + capture + file_coord + rank_coord # pawn capture move e.g. dxe5
m3 = file_coord + "8" + promote + piece # pawn promotion e.g. e8=Q
@@ -50,7 +48,7 @@ m6 = piece + rank_coord + file_coord + rank_coord # piece move e.g. R4a7 m7 = piece + capture + file_coord + rank_coord # piece capture move e.g. Bxh7
m8 = castle_queenside | castle_kingside # castling e.g. o-o
-check = oneOf("+ ++")
+check = one_of("+ ++")
mate = Literal("#")
annotation = Word("!?", max=2)
nag = " $" + Word(nums)
@@ -58,30 +56,28 @@ decoration = check | mate | annotation | nag variant = Forward()
half_move = (
- Combine((m3 | m1 | m2 | m4 | m5 | m6 | m7 | m8) + Optional(decoration))
- + Optional(comment)
- + Optional(variant)
+ Combine((m3 | m1 | m2 | m4 | m5 | m6 | m7 | m8) + Opt(decoration))
+ + Opt(comment)
+ + Opt(variant)
)
-move = Suppress(move_number) + half_move + Optional(half_move)
-variant << "(" + OneOrMore(move) + ")"
+move = Suppress(move_number) + half_move + Opt(half_move)
+variant << "(" + move[1, ...] + ")"
# grouping the plies (half-moves) for each move: useful to group annotations, variants...
# suggested by Paul McGuire :)
-move = Group(Suppress(move_number) + half_move + Optional(half_move))
-variant << Group("(" + OneOrMore(move) + ")")
-game_terminator = oneOf("1-0 0-1 1/2-1/2 *")
+move = Group(Suppress(move_number) + half_move + Opt(half_move))
+variant << Group("(" + move[1, ...] + ")")
+game_terminator = one_of("1-0 0-1 1/2-1/2 *")
pgnGrammar = (
- Suppress(ZeroOrMore(tag)) + ZeroOrMore(move) + Optional(Suppress(game_terminator))
+ Suppress(tag[...]) + move[...] + Opt(Suppress(game_terminator))
)
def parsePGN(pgn, bnf=pgnGrammar, fn=None):
try:
- return bnf.parseString(pgn)
+ return bnf.parse_string(pgn, parse_all=True)
except ParseException as err:
- print(err.line)
- print(" " * (err.column - 1) + "^")
- print(err)
+ print(err.explain())
if __name__ == "__main__":
diff --git a/examples/protobuf_parser.py b/examples/protobuf_parser.py index 92f5a28..f4bc92b 100644 --- a/examples/protobuf_parser.py +++ b/examples/protobuf_parser.py @@ -13,20 +13,19 @@ from pyparsing import ( Suppress, Forward, Group, - oneOf, - ZeroOrMore, - Optional, - delimitedList, - restOfLine, + one_of, + Opt, + DelimitedList, + rest_of_line, quotedString, Dict, Keyword, ) -ident = Word(alphas + "_", alphanums + "_").setName("identifier") +ident = Word(alphas + "_", alphanums + "_").set_name("identifier") integer = Regex(r"[+-]?\d+") -LBRACE, RBRACE, LBRACK, RBRACK, LPAR, RPAR, EQ, SEMI = map(Suppress, "{}[]()=;") +LBRACE, RBRACE, LBRACK, RBRACK, LPAR, RPAR, EQ, SEMI = Suppress.using_each("{}[]()=;") kwds = """message required optional repeated enum extensions extends extend to package service rpc returns true false option import syntax""" @@ -38,9 +37,9 @@ messageBody = Forward() messageDefn = MESSAGE_ - ident("messageId") + LBRACE + messageBody("body") + RBRACE typespec = ( - oneOf( - """double float int32 int64 uint32 uint64 sint32 sint64 - fixed32 fixed64 sfixed32 sfixed64 bool string bytes""" + one_of( + "double float int32 int64 uint32 uint64 sint32 sint64" + " fixed32 fixed64 sfixed32 sfixed64 bool string bytes" ) | ident ) @@ -48,12 +47,12 @@ rvalue = integer | TRUE_ | FALSE_ | ident fieldDirective = LBRACK + Group(ident + EQ + rvalue) + RBRACK fieldDefnPrefix = REQUIRED_ | OPTIONAL_ | REPEATED_ fieldDefn = ( - Optional(fieldDefnPrefix) + Opt(fieldDefnPrefix) + typespec("typespec") + ident("ident") + EQ + integer("fieldint") - + ZeroOrMore(fieldDirective) + + fieldDirective[...] + SEMI ) @@ -62,7 +61,7 @@ enumDefn = ( ENUM_("typespec") - ident("name") + LBRACE - + Dict(ZeroOrMore(Group(ident + EQ + integer + SEMI)))("values") + + Dict((Group(ident + EQ + integer + SEMI))[...])("values") + RBRACE ) @@ -73,10 +72,10 @@ extensionsDefn = EXTENSIONS_ - integer + TO_ + integer + SEMI messageExtension = EXTEND_ - ident + LBRACE + messageBody + RBRACE # messageBody ::= { fieldDefn | enumDefn | messageDefn | extensionsDefn | messageExtension }* -messageBody << Group( - ZeroOrMore( - Group(fieldDefn | enumDefn | messageDefn | extensionsDefn | messageExtension) - ) +messageBody <<= Group( + Group( + fieldDefn | enumDefn | messageDefn | extensionsDefn | messageExtension + )[...] ) # methodDefn ::= 'rpc' ident '(' [ ident ] ')' 'returns' '(' [ ident ] ')' ';' @@ -84,25 +83,25 @@ methodDefn = ( RPC_ - ident("methodName") + LPAR - + Optional(ident("methodParam")) + + Opt(ident("methodParam")) + RPAR + RETURNS_ + LPAR - + Optional(ident("methodReturn")) + + Opt(ident("methodReturn")) + RPAR ) # serviceDefn ::= 'service' ident '{' methodDefn* '}' serviceDefn = ( - SERVICE_ - ident("serviceName") + LBRACE + ZeroOrMore(Group(methodDefn)) + RBRACE + SERVICE_ - ident("serviceName") + LBRACE + Group(methodDefn)[...] + RBRACE ) syntaxDefn = SYNTAX_ + EQ - quotedString("syntaxString") + SEMI # packageDirective ::= 'package' ident [ '.' ident]* ';' -packageDirective = Group(PACKAGE_ - delimitedList(ident, ".", combine=True) + SEMI) +packageDirective = Group(PACKAGE_ - DelimitedList(ident, ".", combine=True) + SEMI) -comment = "//" + restOfLine +comment = "//" + rest_of_line importDirective = IMPORT_ - quotedString("importFileSpec") + SEMI @@ -120,10 +119,11 @@ topLevelStatement = Group( | syntaxDefn ) -parser = Optional(packageDirective) + ZeroOrMore(topLevelStatement) +parser = Opt(packageDirective) + topLevelStatement[...] parser.ignore(comment) + if __name__ == "__main__": test1 = """message Person { @@ -168,4 +168,4 @@ if __name__ == "__main__": } """ - parser.runTests([test1, test2, test3]) + parser.run_tests([test1, test2, test3]) diff --git a/examples/rangeCheck.py b/examples/rangeCheck.py index 2d1d2c8..be54833 100644 --- a/examples/rangeCheck.py +++ b/examples/rangeCheck.py @@ -8,7 +8,7 @@ # Copyright 2011,2015 Paul T. McGuire
#
-from pyparsing import Word, nums, Suppress, Optional
+from pyparsing import Word, nums, Suppress, Opt
from datetime import datetime
@@ -30,11 +30,11 @@ def ranged_value(expr, minval=None, maxval=None): (False, False): "value is not in the range ({} to {})".format(minval, maxval),
}[minval is None, maxval is None]
- return expr().addCondition(inRangeCondition, message=outOfRangeMessage)
+ return expr().add_condition(inRangeCondition, message=outOfRangeMessage)
# define the expressions for a date of the form YYYY/MM/DD or YYYY/MM (assumes YYYY/MM/01)
-integer = Word(nums).setName("integer")
+integer = Word(nums).set_name("integer")
integer.setParseAction(lambda t: int(t[0]))
month = ranged_value(integer, 1, 12)
@@ -42,11 +42,11 @@ 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")
+dateExpr = year("year") + SLASH + month("month") + Opt(SLASH + day("day"))
+dateExpr.set_name("date")
# convert date fields to datetime (also validates dates as truly valid dates)
-dateExpr.setParseAction(lambda t: datetime(t.year, t.month, t.day or 1).date())
+dateExpr.set_parse_action(lambda t: datetime(t.year, t.month, t.day or 1).date())
# add range checking on dates
mindate = datetime(2002, 1, 1).date()
@@ -54,7 +54,7 @@ maxdate = datetime.now().date() dateExpr = ranged_value(dateExpr, mindate, maxdate)
-dateExpr.runTests(
+dateExpr.run_tests(
"""
2011/5/8
2001/1/1
|