本文整理汇总了Python中pyparsing.Forward.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Forward.setParseAction方法的具体用法?Python Forward.setParseAction怎么用?Python Forward.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Forward
的用法示例。
在下文中一共展示了Forward.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_constraint_group
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def parse_constraint_group(constraint_group):
global valgrind_operations, size_by_var, offset_by_var, realsize_by_var, shift_by_var
init_global_vars()
lparen = Literal("(")
rparen = Literal(")")
func = Word(alphanums, alphanums+":_")
integer = Word(nums)
expression = Forward()
arg = expression | func | integer
args = arg + ZeroOrMore(","+arg)
expression << func + lparen + args + rparen
expression.setParseAction(parse_function)
valgrind_operations_group = []
for constraint in constraint_group:
valgrind_operations = []
expression.parseString(constraint)
resize_operands()
valgrind_operations_group.append(valgrind_operations)
return (valgrind_operations_group, size_by_var, offset_by_var, realsize_by_var, shift_by_var)
示例2: parser
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def parser():
rule = Forward()
body = OneOrMore(CharsNotIn('{};') + ';')
sel = CharsNotIn('{};')
rule <<= sel + Group( '{' + ZeroOrMore( rule | body ) + '}' )
rule.setParseAction( make_action(Rule) )
stylesheet = ZeroOrMore( rule )
stylesheet.ignore( cStyleComment )
return stylesheet
示例3: main
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def main(s):
lpar = Literal('(').suppress()
rpar = Literal(')').suppress()
integer = Word(nums)
element = Word(alphas, exact=1)
formula = Forward()
term = Group((element | Group(lpar + formula + rpar)('subgroup')) +
Optional(integer, default=1)('mult'))
formula << OneOrMore(term)
integer.setParseAction(process_integer)
term.setParseAction(process_term)
formula.setParseAction(process_formula)
return formula.parseString(s)[0]
示例4: __setup_parser
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def __setup_parser():
# reserved single-character tokens
LSQUARE,RSQUARE,LCURLY,RCURLY,EQ,PIPE,SEMI = map(Suppress,'[]{}=|;')
# non-iterable literals
integer = simple(Word('-'+nums,nums), 'int', int)
string = simple(QuotedString("'") | QuotedString('"'), 'str', str)
regex = simple(QuotedString('/'), 'rgx', re.compile)
# list/range literals
emptylist = named(LSQUARE + RSQUARE, 'emptylist')
rstart = LSQUARE + integer + Optional(Suppress(',') + integer)
irange = named(rstart + Suppress('..]'), 'irange')
brange = named(rstart + Suppress('..') + integer + RSQUARE, 'brange')
intlist = named(LSQUARE + delimitedList(integer) + RSQUARE, 'intlist')
strlist = named(LSQUARE + delimitedList(string) + RSQUARE, 'strlist')
rgxlist = named(LSQUARE + delimitedList(regex) + RSQUARE, 'rgxlist')
list_lit = Forward()
lstlist = named(LSQUARE + delimitedList(list_lit) + RSQUARE, 'lstlist')
list_lit << (emptylist | irange | brange | intlist | strlist | rgxlist | lstlist)
# special-syntax functions
slurp = special(QuotedString('<',endQuoteChar='>'), 'slurp')
shell = special(QuotedString('`'), 'shell')
# functions and arguments
name = simple(Word(alphas, alphanums+'_'), 'name', str)
subpipe = Forward()
function = Forward()
argument = string | list_lit | regex | integer | subpipe | slurp | shell | function
function << name + named(ZeroOrMore(argument), 'arguments')
function.setParseAction(lambda parse: ('function', dict(parse.asList())))
# an atom is anything that can fit between pipes on its own
atom = (function | slurp | shell | list_lit)
# an expression/subpipe is multiple atoms piped together
expression = named(atom + ZeroOrMore(PIPE + atom), 'pipe')
subpipe << LCURLY + expression + RCURLY
# statements and lines are pretty standard
statement = Optional(name + EQ, default=('name','')) + expression
statement.setParseAction(lambda parse: dict(parse.asList()))
line = (statement | empty).ignore(pythonStyleComment)
return line.parseString
示例5: _build_grammar
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def _build_grammar(self):
expr = Forward()
float_lit = Combine(Word(nums) + '.' + Word(nums))
float_lit.setName('float')
float_lit.setParseAction(lambda x: \
self.to_literal(float(x[0])))
int_lit = Word(nums)
int_lit.setName('int')
int_lit.setParseAction(lambda x: \
self.to_literal(int(x[0])))
num = (float_lit | int_lit)
num.setParseAction(lambda x: x[0])
tag_name = Word(alphas + "_", alphanums + "_")
tag_name.setName('tag_name')
tag_name.setParseAction(lambda t: tag_reference.TagReference(t[0]))
quoted_string = QuotedString("'")
quoted_string.setParseAction(lambda s: self.to_literal(s[0]))
oper = oneOf('+ * / -')
oper.setParseAction(lambda o: o[0])
lpar = Literal("(").suppress()
rpar = Literal(")").suppress()
arith = Group(lpar + expr + oper + expr + rpar)
arith.setParseAction(lambda t: \
self.to_arith(t[0][0], t[0][1], t[0][2]))
assign = tag_name + '=' + expr
assign.setName('assign')
assign.setParseAction(lambda x: self.to_assign(x[0],x[2]))
print_tags = Literal('?')
print_tags.setParseAction(lambda x: self.to_print_tags())
expr <<(arith|assign|tag_name|num|quoted_string|print_tags)
expr.setParseAction(lambda x: x[0])
return expr
示例6: create_bnf
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def create_bnf():
cvt_int = lambda toks: int(toks[0])
cvt_real = lambda toks: float(toks[0])
cvt_tuple = lambda toks : tuple(toks.asList())
cvt_dict = lambda toks: dict(toks.asList())
# define punctuation as suppressed literals
(lparen, rparen, lbrack, rbrack,
lbrace, rbrace, colon) = map(Suppress,"()[]{}:")
integer = Combine(Optional(oneOf("+ -")) + Word(nums)).setName("integer")
integer.setParseAction(cvt_int)
real = Combine(Optional(oneOf("+ -"))+ Word(nums)
+ "." + Optional(Word(nums))
+ Optional("e" + Optional(oneOf("+ -"))
+ Word(nums))).setName("real")
real.setParseAction(cvt_real)
tuple_str = Forward()
list_str = Forward()
dict_str = Forward()
list_item = (real | integer | Group(list_str) | tuple_str | dict_str
| quotedString.setParseAction(removeQuotes)
| Word(alphas8bit + alphas, alphas8bit + alphanums + "_"))
list_item2 = list_item | Empty().setParseAction(lambda: [None])
tuple_str << (Suppress("(") + Optional(delimitedList(list_item)) +
Optional(Suppress(",")) + Suppress(")"))
tuple_str.setParseAction(cvt_tuple)
list_str << (lbrack + Optional(delimitedList(list_item) +
Optional(Suppress(","))) + rbrack)
dict_entry = Group(list_item + colon + list_item2)
dict_inner = delimitedList(dict_entry) + Optional(Suppress(","))
dict_inner.setParseAction(cvt_dict)
dict_str << (lbrace + Optional(dict_inner) + rbrace)
return dict_inner
示例7: get_sort_expression
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def get_sort_expression():
value_expression = Word(srange("[a-zA-Z0-9_.*]"))
value_expression.setParseAction(lambda tokens: tokens[0])
quoted_value_expression = Word('"').suppress() +\
value_expression + Word('"').suppress()
option_value = value_expression | quoted_value_expression
option_value.setParseAction(lambda tokens: tokens[0])
simple_option = Word(srange("[a-zA-Z0-9_.*]")) +\
Word(':').suppress() + option_value
simple_option.setParseAction(lambda tokens: (tokens[0], tokens[1]))
option = Forward()
option << (simple_option |
(Word(srange("[a-zA-Z0-9_.*]")) +
Word(':').suppress() +
nestedExpr(content=option)))
option.setParseAction(
lambda tokens: parse_sort_field_option(tokens.asList())
)
exp = option + ZeroOrMore(Word(',').suppress() + option)
field_expression = Optional('-') + Word(
srange("[a-zA-Z0-9_.*]")
) + Optional(nestedExpr(content=exp))
field_expression.setParseAction(parse_sort_field_expression)
fields_expression = field_expression + ZeroOrMore(
Word(',').suppress() + field_expression)
fields_expression.setParseAction(parse_sort_expression)
sort_expression = Word('sort:').suppress() \
+ Word('[').suppress() \
+ fields_expression + Word(']').suppress()
return sort_expression
示例8: parse_pabl
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def parse_pabl(self, raw_pabl):
INDENT = lineEnd.suppress() + empty + empty.copy().setParseAction(
self.check_sub_indent)
UNDENT = FollowedBy(empty).setParseAction(self.check_unindent)
UNDENT.setParseAction(self.unindent)
terminator = Literal(';').suppress()
comment = Literal('#') + restOfLine
item_name = Word(alphas, alphanums + '_')
variable = Word(alphas, alphanums + '_.')
variable_as = (variable + 'as' + item_name)
stmt = Forward()
suite = Group(
OneOrMore(empty + stmt.setParseAction(self.check_peer_indent)))
suite.ignore(comment)
item_start = Literal('@item').suppress()
item_end = Literal(':').suppress()
permission_start = Literal('@permissions')
item_decl = (item_start + item_name.setResultsName('item') + item_end)
item_defn = Group(item_decl + INDENT + suite + UNDENT)
permission_decl = (permission_start + Group(
delimitedList(item_name).setResultsName('permissions')) + item_end)
permission_defn = Group(permission_decl + INDENT + suite + UNDENT)
fieldList = delimitedList(
Group(variable_as) | variable
).setResultsName('fields') + terminator
stmt << (item_defn | fieldList | Group(permission_defn))
parseTree = suite.parseString(raw_pabl)
return parseTree
示例9: evaluator
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
#.........这里部分代码省略.........
x = reduce(lambda a, b: b ** a, x)
return x
def parallel(x): # Parallel resistors [ 1 2 ] => 2/3
# convert from pyparsing.ParseResults, which doesn't support '0 in x'
x = list(x)
if len(x) == 1:
return x[0]
if 0 in x:
return float('nan')
x = [1. / e for e in x if isinstance(e, numbers.Number)] # Ignore ||
return 1. / sum(x)
def sum_parse_action(x): # [ 1 + 2 - 3 ] -> 0
total = 0.0
op = ops['+']
for e in x:
if e in set('+-'):
op = ops[e]
else:
total = op(total, e)
return total
def prod_parse_action(x): # [ 1 * 2 / 3 ] => 0.66
prod = 1.0
op = ops['*']
for e in x:
if e in set('*/'):
op = ops[e]
else:
prod = op(prod, e)
return prod
def func_parse_action(x):
return [all_functions[x[0]](x[1])]
# SI suffixes and percent
number_suffix = reduce(lambda a, b: a | b, map(
Literal, suffixes.keys()), NoMatch())
(dot, minus, plus, times, div, lpar, rpar, exp) = map(Literal, ".-+*/()^")
number_part = Word(nums)
# 0.33 or 7 or .34 or 16.
inner_number = (number_part + Optional(
"." + Optional(number_part))) | ("." + number_part)
# 0.33k or -17
number = (Optional(minus | plus) + inner_number
+ Optional(CaselessLiteral("E") + Optional(
(plus | minus)) + number_part)
+ Optional(number_suffix))
number = number.setParseAction(number_parse_action) # Convert to number
# Predefine recursive variables
expr = Forward()
factor = Forward()
def sreduce(f, l):
''' Same as reduce, but handle len 1 and len 0 lists sensibly '''
if len(l) == 0:
return NoMatch()
if len(l) == 1:
return l[0]
return reduce(f, l)
# Handle variables passed in. E.g. if we have {'R':0.5}, we make the substitution.
# Special case for no variables because of how we understand PyParsing is
# put together
if len(all_variables) > 0:
# We sort the list so that var names (like "e2") match before
# mathematical constants (like "e"). This is kind of a hack.
all_variables_keys = sorted(
all_variables.keys(), key=len, reverse=True)
varnames = sreduce(lambda x, y: x | y, map(
lambda x: CasedLiteral(x), all_variables_keys))
varnames.setParseAction(lambda x: map(lambda y: all_variables[y], x))
else:
varnames = NoMatch()
# Same thing for functions.
if len(all_functions) > 0:
funcnames = sreduce(lambda x, y: x | y,
map(lambda x: CasedLiteral(x), all_functions.keys()))
function = funcnames + lpar.suppress() + expr + rpar.suppress()
function.setParseAction(func_parse_action)
else:
function = NoMatch()
atom = number | function | varnames | lpar + expr + rpar
factor << (atom + ZeroOrMore(
exp + atom)).setParseAction(exp_parse_action) # 7^6
paritem = factor + ZeroOrMore(Literal('||') + factor) # 5k || 4k
paritem = paritem.setParseAction(parallel)
term = paritem + ZeroOrMore((times | div) + paritem) # 7 * 5 / 4 - 3
term = term.setParseAction(prod_parse_action)
expr << Optional((plus | minus)) + term + ZeroOrMore(
(plus | minus) + term) # -5 + 4 - 3
expr = expr.setParseAction(sum_parse_action)
return (expr + stringEnd).parseString(string)[0]
示例10: Regex
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
number = Regex(r'\d+(\.\d+)?').setParseAction(lambda t:float(t[0]))
fuzzy_modifier = TILDE + Optional(number, default=0.5)("fuzzy")
term = Forward()
field_name = valid_word.copy().setName("fieldname")
incl_range_search = Group(LBRACK + term("lower") + to_ + term("upper") + RBRACK)
excl_range_search = 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))
term.setParseAction(lambda t:[t] if 'field' in t or 'boost' in t else None)
expression << operatorPrecedence(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),
])
# test strings taken from grammar description doc, and TestQueryParser.java
tests = r"""
a and b
a and not b
a and !b
a && !b
示例11: Identifier
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
return Identifier(name)
def process_function(toks):
return FunctionLiteral(toks[0])
comment = '%' + restOfLine
lbrace = Suppress('{')
rbrace = Suppress('}')
intLiteral = Regex(r'#-?\d+').setParseAction(process_int_literal)
stringLiteral = QuotedString('"').setParseAction(process_string_literal)
restrictedPrintables = ''.join(c for c in printables if not c in '#%^&{}~\\')
nonnums = ''.join(c for c in restrictedPrintables if not c.isdigit())
identifier = Word(nonnums, restrictedPrintables).setParseAction(process_identifier)
token = stringLiteral | intLiteral | identifier
tokenList = Forward()
tokenList.setParseAction(process_function)
tokenList << Group(lbrace + ZeroOrMore(token | tokenList) + rbrace)
commandName = Word(alphas).setParseAction(downcaseTokens)
arg = Group(lbrace + ZeroOrMore(token | tokenList) + rbrace)
command = commandName + ZeroOrMore(arg)
bstGrammar = OneOrMore(command) + StringEnd()
# sloooooow
# bstGrammar.ignore(comment)
# somewhat faster
def strip_comment(line):
"""Strip the commented part of the line."
>>> print strip_comment('a normal line')
a normal line
示例12: len
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
# Ni%1Rh%1((SiO2)%10Al2O3)
# Ni%1Rh%1(Al2O3)
# (Si0.8Er0.2O2)%10Al2O3
dopeMass = matrixMass * wt / (100. - dopewtPercentsSum)
for e in dopes:
if e[1] == dg:
e[0][1] = e[0][1].real * dopeMass / m
else:
elementsList = [t[0] for t in tokens]
duplicates = len(elementsList) > len(set(elementsList))
if duplicates:
dd = defaultdict(int)
for t in tokens:
dd[t[0]] += t[1]
nt = ParseResults([ParseResults([k, v]) for k, v in dd.items()])
formula.setParseAction(sum_by_element)
def round_to_n(x, n=3):
res = x
try:
res = round(x, -int(floor(log10(x))) + n-1) if \
isinstance(x, (float, np.float32, np.float64)) else x
# res = round(x, -int(floor(log10(x))) + n-1)
except (ValueError, OverflowError):
pass
return res
def reconstruct(parsed):
outStr = ''
示例13: Forward
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
expr = Forward()
atom = operand | lpar + expr + rpar
prev_pattern = atom
atom.setParseAction(toExpression)
from pyparsing import Optional
for opers in PRECEDENCE:
pattern_list = []
# only accepts unary and binary operation
# as there are no ternary in boolean
for op in opers:
if op in UNARY:
alternative = Forward()
alternative << (oper_literals[op] + (prev_pattern | alternative))
alternative.setParseAction(toExpression)
unary_pattern = prev_pattern | alternative
pattern_list.append(unary_pattern)
elif op in BINARY:
rest = oper_literals[op] + prev_pattern
rest.setParseAction(toExpression)
binary_pattern = prev_pattern + ZeroOrMore(rest)
pattern_list.append(binary_pattern)
else:
raise Exception(op)
if len(pattern_list) == 1:
prev_pattern = pattern_list[0]
else:
prev_pattern = Or(pattern_list)
示例14: Group
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
signless_mult_expr.setParseAction(operators.InfixLeftSymbol.process)
signless_mult_term = ( signless_mult_expr | sign_term )
# Multiplication.
mult_expr = Group( signless_mult_term + OneOrMore(multop + signless_mult_term) )
mult_expr.setParseAction(operators.InfixLeftSymbol.process)
mult_term = ( mult_expr | signless_mult_term )
# Addition.
add_expr = Group( mult_term + OneOrMore( addop + mult_term ) )
add_expr.setParseAction(operators.InfixLeftSymbol.process)
add_term = ( add_expr | mult_term )
# Complete expression.
expr <<= add_term
expr.setParseAction(operators.Expression.process)
# A unit expression, containing only units. ############################
unit_expr = Forward()
single_unit = identifier.copy()
single_unit.setParseAction(operators.Unit.process)
literal_one = Literal("1")
literal_one.setParseAction(operators.Unit.process_dimensionless)
# The one allows for example for 1/h = h^-1.
unit_term = single_unit | literal_one | ( lpar + unit_expr + rpar )
# Exponent
示例15: formula_grammar
# 需要导入模块: from pyparsing import Forward [as 别名]
# 或者: from pyparsing.Forward import setParseAction [as 别名]
def formula_grammar(table):
"""
Construct a parser for molecular formulas.
:Parameters:
*table* = None : PeriodicTable
If table is specified, then elements and their associated fields
will be chosen from that periodic table rather than the default.
:Returns:
*parser* : pyparsing.ParserElement.
The ``parser.parseString()`` method returns a list of
pairs (*count,fragment*), where fragment is an *isotope*,
an *element* or a list of pairs (*count,fragment*).
"""
# Recursive
composite = Forward()
mixture = Forward()
# whitespace and separators
space = Optional(White().suppress())
separator = space+Literal('+').suppress()+space
# Lookup the element in the element table
symbol = Regex("[A-Z][a-z]*")
symbol = symbol.setParseAction(lambda s,l,t: table.symbol(t[0]))
# Translate isotope
openiso = Literal('[').suppress()
closeiso = Literal(']').suppress()
isotope = Optional(~White()+openiso+Regex("[1-9][0-9]*")+closeiso,
default='0')
isotope = isotope.setParseAction(lambda s,l,t: int(t[0]) if t[0] else 0)
# Translate ion
openion = Literal('{').suppress()
closeion = Literal('}').suppress()
ion = Optional(~White()
+openion
+Regex("([1-9][0-9]*)?[+-]")
+closeion,
default='0+')
ion = ion.setParseAction(lambda s,l,t: int(t[0][-1]+(t[0][:-1] if len(t[0])>1 else '1')))
# Translate counts
fract = Regex("(0|[1-9][0-9]*|)([.][0-9]*)")
fract = fract.setParseAction(lambda s,l,t: float(t[0]) if t[0] else 1)
whole = Regex("[1-9][0-9]*")
whole = whole.setParseAction(lambda s,l,t: int(t[0]) if t[0] else 1)
count = Optional(~White()+(fract|whole),default=1)
# Convert symbol,isotope,ion,count to (count,isotope)
element = symbol+isotope+ion+count
def convert_element(string,location,tokens):
#print "convert_element received",tokens
symbol,isotope,ion,count = tokens[0:4]
if isotope != 0: symbol = symbol[isotope]
if ion != 0: symbol = symbol.ion[ion]
return (count,symbol)
element = element.setParseAction(convert_element)
# Convert "count elements" to a pair
implicit_group = count+OneOrMore(element)
def convert_implicit(string,location,tokens):
#print "implicit",tokens
count = tokens[0]
fragment = tokens[1:]
return fragment if count==1 else (count,fragment)
implicit_group = implicit_group.setParseAction(convert_implicit)
# Convert "(composite) count" to a pair
opengrp = space + Literal('(').suppress() + space
closegrp = space + Literal(')').suppress() + space
explicit_group = opengrp + composite + closegrp + count
def convert_explicit(string,location,tokens):
#print "explicit",tokens
count = tokens[-1]
fragment = tokens[:-1]
return fragment if count == 1 else (count,fragment)
explicit_group = explicit_group.setParseAction(convert_explicit)
# Build composite from a set of groups
group = implicit_group | explicit_group
implicit_separator = separator | space
composite << group + ZeroOrMore(implicit_separator + group)
density = Literal('@').suppress() + count + Optional(Regex("[ni]"),default='i')
compound = composite + Optional(density,default=None)
def convert_compound(string,location,tokens):
#print "compound",tokens
if tokens[-1] is None:
return Formula(structure=_immutable(tokens[:-1]))
elif tokens[-1] == 'n':
return Formula(structure=_immutable(tokens[:-2]), natural_density=tokens[-2])
else:
return Formula(structure=_immutable(tokens[:-2]), density=tokens[-2])
compound = compound.setParseAction(convert_compound)
#.........这里部分代码省略.........