本文整理汇总了Python中pyparsing.Group.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Group.setParseAction方法的具体用法?Python Group.setParseAction怎么用?Python Group.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Group
的用法示例。
在下文中一共展示了Group.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _define_context_component
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def _define_context_component (self, cluster, base_feature_set):
placeholder = Literal(SOURCE_PLACEHOLDER)
placeholder.setParseAction(self._handle_placeholder)
context_component = Group(ZeroOrMore(cluster ^ base_feature_set) + \
placeholder + ZeroOrMore(cluster ^ base_feature_set)).setResultsName('context_component')
context_component.setParseAction(self._handle_context_component)
return context_component
示例2: list_dict
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def list_dict(word=word_free):
"""
Return the pyparsing lexical element, that parses a string either as a list
or as a dictionary.
Parameters
----------
word : lexical element
A custom lexical element for word.
Returns
-------
ld : lexical element
The returned lexical element parses a string in the form
``..., ..., ...`` or ``key1:..., key2=..., key3: ...``
where ``...`` is a ``list_item`` from :func:`get_standard_type_defs()`
and interprets it as a list or a dictionary.
"""
defs = get_standard_type_defs(word)
i = defs['list_item']
arg = i.copy()
arg.setParseAction(lambda t: (t[0],))
narg = word_strict + (colon | equal_sign) + i
narg.setParseAction(lambda t: (t[0], t[1]))
ld = Group(list_of(narg | arg))
ld.setParseAction(lambda t: ([x[0] for x in t[0] if len(x) == 1],
dict([x for x in t[0] if len(x) > 1]))
)
return ld
示例3: __init__
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def __init__(self, ffilter, queue_out):
FuzzQueue.__init__(self, queue_out)
Thread.__init__(self)
self.setName('filter_thread')
self.queue_out = queue_out
if PYPARSING:
element = oneOf("c l w h")
digits = "XB0123456789"
integer = Word( digits )#.setParseAction( self.__convertIntegers )
elementRef = Group(element + oneOf("= != < > >= <=") + integer)
operator = oneOf("and or")
definition = elementRef + ZeroOrMore( operator + elementRef)
nestedformula = Group(Suppress(Optional(Literal("("))) + definition + Suppress(Optional(Literal(")"))))
self.finalformula = nestedformula + ZeroOrMore( operator + nestedformula)
elementRef.setParseAction(self.__compute_element)
nestedformula.setParseAction(self.__compute_formula)
self.finalformula.setParseAction(self.__myreduce)
self.res = None
self.hideparams = ffilter
if "XXX" in self.hideparams['codes']:
self.hideparams['codes'].append("0")
self.baseline = None
示例4: get_parse_expression
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def get_parse_expression(parse_func, parse_var_id):
"""return a parse expression with for the
input parseActions
"""
var_id = Group(FUNC_NAME + COLON + IDENTIFIER) | REAL | INTEGER | IDENTIFIER
var_id.setParseAction(parse_var_id)
# Forward declaration for an Arithmetic Expression
arith_expr = Forward()
func_call = Group(FUNC_NAME + LPAREN + Optional(Group(delimitedList(arith_expr))) + RPAREN)
# An Arithmetic expression can have a var_id or
# a function call as an operand
# pylint: disable=expression-not-assigned
arith_expr << operatorPrecedence(
func_call | var_id,
[
(EXPONENTIATION_OPS, 2, opAssoc.LEFT, eval_binary_op),
(UNARY_OPS, 1, opAssoc.RIGHT, eval_unary_op),
(MULT_OPS, 2, opAssoc.LEFT, eval_binary_op),
(SUM_OPS, 2, opAssoc.LEFT, eval_binary_op),
(REL_OPS, 2, opAssoc.LEFT, eval_binary_op),
(LOGICAL_OPS, 2, opAssoc.LEFT, eval_binary_op),
],
)
# pylint: enable=expression-not-assigned
# Argument expression for a function call
# An argument to a function can be an
# IDENTIFIER, Arithmetic expression, REAL number, INTEGER or a
# Function call itself
func_call.setParseAction(parse_func)
return arith_expr
示例5: ifParser
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def ifParser():
comma = Literal(",").suppress()
hash = Literal("#").suppress()
equal = Literal("=").suppress()
# Rules and labels
rulename = Word (alphanums + "_")
rulecategory = oneOf("Protocol_Rules Invariant_Rules Decomposition_Rules Intruder_Rules Init Goal")
label = hash + Literal("lb") + equal + rulename + comma + Literal("type") + equal + rulecategory
labeledrule = Group(label) + Group(ruleParser())
def labeledruleAction(s,l,t):
if t[0][3] == "Protocol_Rules":
print "-----------------"
print "- Detected rule -"
print "-----------------"
print t[0]
print t[1]
print
labeledrule.setParseAction(labeledruleAction)
# A complete file
parser = OneOrMore(labeledrule)
parser.ignore("##" + restOfLine)
return parser
示例6: split_chemical_formula
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def split_chemical_formula(formula):
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def replace_things(stringg, listt, replacement):
for x in listt:
stringg = stringg.replace(x, replacement)
return stringg
bad_chars = ["(", ")", "-", "."]
formula = replace_things(formula, bad_chars, "|")
if is_number(formula):
return [["", 0]]
if len(formula) == 0:
return [["", 0]]
# define some strings to use later, when describing valid lists
# of characters for chemical symbols and numbers
caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowers = caps.lower()
digits = "0123456789"
# Version 1
# Version 2 - Auto-convert integers, and add results names
def convertIntegers(tokens):
return int(tokens[0])
element = Word(caps, lowers)
integer = Word(digits).setParseAction(convertIntegers)
elementRef = Group(element("symbol") + Optional(integer, default=1)("qty"))
# pre-1.4.7, use this:
# elementRef = Group( element.setResultsName("symbol") + Optional( integer, default=1 ).setResultsName("qty") )
chemicalFormula = OneOrMore(elementRef)
# Version 3 - Compute partial molecular weight per element, simplifying
# summing
# No need to redefine grammar, just define parse action function, and
# attach to elementRef
def computeElementWeight(tokens):
element = tokens[0]
element["weight"] = atomicWeight[element.symbol] * element.qty
elementRef.setParseAction(computeElementWeight)
formulaData = chemicalFormula.parseString(formula)
mw = sum([element.weight for element in formulaData])
return formulaData
示例7: main
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group 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]
示例8: __init__
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
class NodeParser:
def __init__(self):
self.num = Word(nums)
self.header = Regex(r"^UCLA.*")
self.comment = Regex(r"#.*")
self.bkid = Word(alphanums)
self.num_nodes = Literal("NumNodes") + Literal(":") + self.num("NumNodes")
self.num_terminals = Literal("NumTerminals") + Literal(":") + self.num("NumTerminals")
self.size = Group(self.num("width") + self.num("height"))
self.terminal = Optional(Literal("terminal"))
self.node = self.bkid("id") + self.size("size") + self.terminal
self.node_grammar = (
self.header + ZeroOrMore(self.comment) + self.num_nodes + self.num_terminals + OneOrMore(self.node)
)
self.coordinate = Group(self.num("x") + self.num("y"))
self.pl = (
self.bkid("id") + self.coordinate("coordinate") + Suppress(Literal(": N") + Optional(Literal(r"/FIXED")))
)
self.pl_grammar = self.header + ZeroOrMore(self.comment) + OneOrMore(self.pl)
def compute_chip_size(self, benchmark):
benchmark_path = pathlib.Path(os.environ["BENCHMARK"])
node_file = benchmark_path / "ispd2005/{0}/{0}.nodes".format(benchmark)
pl_file = benchmark_path / "ispd2005/{0}/{0}.pl".format(benchmark)
print(node_file.as_posix())
print(pl_file.as_posix())
x_max = 0
y_max = 0
sizes = []
coordinates = []
self.size.setParseAction(lambda tokens: sizes.append([tokens.width, tokens.height]))
self.coordinate.setParseAction(lambda tokens: coordinates.append((tokens.x, tokens.y)))
self.bkid.setParseAction(lambda tokens: print(tokens[0]))
self.node_grammar.parseFile(node_file.as_posix())
self.pl_grammar.parseFile(pl_file.as_posix())
for i in range(len(sizes)):
print(i)
if coordinates[i][0] + sizes[i][0] > x_max:
x_max = coordinates[i][0] + sizes[i][0]
if coordinates[i][1] + sizes[i][1] > y_max:
y_max = coordinates[i][1] + sizes[i][1]
return x_max, y_max
示例9: define_operand
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def define_operand(self):
"""
Return the syntax definition for an operand.
An operand can be a variable, a string, a number or a set. A set
is made of other operands, including other sets.
**This method shouldn't be overridden**. Instead, override the syntax
definitions for variables, strings and/or numbers.
If you want to customize the sets, check :meth:`T_SET_START`,
:meth:`T_SET_END` and :meth:`T_ELEMENT_SEPARATOR`.
"""
identifier = self.define_identifier()
operand = Forward()
# Defining the sets:
set_start = Suppress(self._grammar.get_token("set_start"))
set_end = Suppress(self._grammar.get_token("set_end"))
element_separator = self._grammar.get_token("element_separator")
elements = delimitedList(operand, delim=element_separator)
set_ = Group(set_start + Optional(elements) + set_end)
set_.setParseAction(self.make_set)
set_.setName("set")
# Defining the variables:
variable = identifier.copy()
variable.setName("variable")
variable.addParseAction(self.make_variable)
# Defining the functions:
function_name = identifier.setResultsName("function_name")
function_name.setName("function_name")
args_start = Suppress(self._grammar.get_token("arguments_start"))
args_end = Suppress(self._grammar.get_token("arguments_end"))
args_sep = self._grammar.get_token("arguments_separator")
arguments = Optional(Group(delimitedList(operand, delim=args_sep)),
default=())
arguments = arguments.setResultsName("arguments")
arguments.setParseAction(lambda tokens: tokens[0])
function = function_name + args_start + arguments + args_end
function.setName("function")
function.setParseAction(self.make_function)
operand << (function | variable | self.define_number() | \
self.define_string() | set_)
return operand
示例10: __init__
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def __init__(self):
if PYPARSING:
category = Word( alphas + "_-*", alphanums + "_-*" )
operator = oneOf("and or ,")
neg_operator = "not"
elementRef = category
definition = elementRef + ZeroOrMore( operator + elementRef)
nestedformula = Group(Suppress(Optional(Literal("("))) + definition + Suppress(Optional(Literal(")"))))
neg_nestedformula = Optional(neg_operator) + nestedformula
self.finalformula = neg_nestedformula + ZeroOrMore( operator + neg_nestedformula)
elementRef.setParseAction(self.__compute_element)
neg_nestedformula.setParseAction(self.__compute_neg_formula)
nestedformula.setParseAction(self.__compute_formula)
self.finalformula.setParseAction(self.__myreduce)
示例11: _getPattern
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def _getPattern(self):
arith_expr = Forward()
comp_expr = Forward()
logic_expr = Forward()
LPAR, RPAR, SEMI = map(Suppress, "();")
identifier = Word(alphas+"_", alphanums+"_")
multop = oneOf('* /')
plusop = oneOf('+ -')
expop = Literal( "^" )
compop = oneOf('> < >= <= != ==')
andop = Literal("AND")
orop = Literal("OR")
current_value = Literal( "." )
assign = Literal( "=" )
# notop = Literal('NOT')
function = oneOf(' '.join(self.FUNCTIONS))
function_call = Group(function.setResultsName('fn') + LPAR + Optional(delimitedList(arith_expr)) + RPAR)
aggregate_column = QuotedString(quoteChar='{', endQuoteChar='}')
single_column = QuotedString(quoteChar='[', endQuoteChar=']')
integer = Regex(r"-?\d+")
real = Regex(r"-?\d+\.\d*")
# quotedString enables strings without quotes to pass
operand = \
function_call.setParseAction(self.__evalFunction) | \
aggregate_column.setParseAction(self.__evalAggregateColumn) | \
single_column.setParseAction(self.__evalSingleColumn) | \
((real | integer).setParseAction(self.__evalConstant)) | \
quotedString.setParseAction(self.__evalString).addParseAction(removeQuotes) | \
current_value.setParseAction(self.__evalCurrentValue) | \
identifier.setParseAction(self.__evalString)
arith_expr << operatorPrecedence(operand,
[
(expop, 2, opAssoc.LEFT, self.__expOp),
(multop, 2, opAssoc.LEFT, self.__multOp),
(plusop, 2, opAssoc.LEFT, self.__addOp),
])
# comp_expr = Group(arith_expr + compop + arith_expr)
comp_expr << operatorPrecedence(arith_expr,
[
(compop, 2, opAssoc.LEFT, self.__evalComparisonOp),
])
logic_expr << operatorPrecedence(comp_expr,
[
(andop, 2, opAssoc.LEFT, self.__evalLogicOp),
(orop, 2, opAssoc.LEFT, self.__evalLogicOp)
])
pattern = logic_expr + StringEnd()
return pattern
示例12: __init__
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def __init__(self, max_=60):
# define the grammar structure
digits = "0123456789"
star = Literal('*')
number = Word(digits) | Word(alphas)
steps = number
range_ = number + Optional(Literal('-') + number)
numspec = star | range_
expr = Group(numspec) + Optional(Literal('/') + steps)
extra_groups = ZeroOrMore(Literal(',') + expr)
groups = expr + extra_groups + StringEnd()
# define parse actions
star.setParseAction(self._expand_star)
number.setParseAction(self._expand_number)
range_.setParseAction(self._expand_range)
expr.setParseAction(self._filter_steps)
extra_groups.setParseAction(self._ignore_comma)
groups.setParseAction(self._join_to_set)
self.max_ = max_
self.parser = groups
示例13: parse_create_view
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
def parse_create_view(string):
"""Parse the create view sql query and return metadata
Args:
string(str): Input sql string that should be parsed
Returns:
view_data(dict): view_data dictionary for instantiating a view object
"""
string = rreplace(string, ')', ' )')
end = ')' + StringEnd()
select = Group(ZeroOrMore(~end + Word(printables)))
parser = _create + replace_check.setResultsName('replace') + _view
parser += _db_name.setResultsName('view_name') + _as + '('
parser += select.setParseAction(merge).setResultsName('select_statement')
parser += end
# Parse the base table definitions
view_data = to_dict(parser.parseString(string))
return view_data
示例14: Optional
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
RETURNS + LPAR + Optional(identifier("response")) + RPAR))("method_definition")
method_definition.setParseAction(method_definition_fn)
service_definition= (SERVICE - identifier("service") + LBRACE + ZeroOrMore(Group(method_definition)) + RBRACE)("service_definition")
service_definition.setParseAction(service_definition_fn)
package_directive = (Group(PACKAGE - delimitedList(identifier, '.', combine=True) + SEMI))("package_directive")
package_directive.setParseAction(package_directive_fn)
import_directive = IMPORT - quotedString("import") + SEMI
import_directive.setParseAction(import_directive_fn)
option_directive = OPTION - identifier("option") + EQ + (integer | quotedString)("value") + SEMI
top_level_statement = Group(message_definition| enum_definition| option_directive | import_directive | service_definition)("top_level_statement")
top_level_statement.setParseAction(top_level_statement_fn)
syntax_directive = (SYNTAX + EQ + quotedString("syntax_version") + SEMI)("syntax_directive")
parser = (Optional(syntax_directive) + Optional(package_directive) + ZeroOrMore(top_level_statement))("parser")
parser.setParseAction(parser_fn)
comment = '//' + restOfLine
parser.ignore(comment)
test2 = """message Person {
required uint32 id = 1;
required string name = 2;
optional string email = 3;
optional Person person = 4;
}"""
示例15: Word
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import setParseAction [as 别名]
ident = Word(alphas, alphanums + "_$" ) ^ QuotedString('"') ^ QuotedString("`")
ident.setParseAction(lambda toks: ['"%s"' % toks[0]])
string = QuotedString("'",multiline=True)
string.setParseAction(lambda toks: ["'%s'" % toks[0]])
columnName = delimitedList( ident, ".",combine=True)
tableName = delimitedList( ident, ".",combine=True)
dataType = Word(alphas) + Combine(Optional(Literal("(") + (Word(nums) ^ delimitedList(string,combine=True)) + Literal(")"))) + ZeroOrMore(nnToken ^ autoincrementToken ^ (defaultToken + (string ^ nullToken)) ^ unsignedToken.suppress() )
dataType.setParseAction(convert_datatypes)
columnDescription = Group(ident + dataType)
keyDescription = Optional(primaryToken ^ uniqueToken) + keyToken + Optional(ident) + Literal("(") + delimitedList(ident + Optional(Literal("(") + Word(nums) + Literal(")"))) + Literal(")")
createTableStmt = Group(createToken + tableToken + ifneToken + ident + Literal("(")) + delimitedList(columnDescription ^ keyDescription.suppress()) + Group(Literal(")")) + Optional(autoincrementToken + Literal("=") + Word(nums)).suppress()
createTableStmt.setParseAction(rebuild_createtable)
createDataBaseStmt = Group(createToken + databaseToken + ident + dcsToken + Word(alphanums)+ collateToken + ident)
useStmt = Group(useToken + ident)
comment = LineStart() + CharsNotIn("\n") + LineEnd()
value = Group(Literal("(") + delimitedList(Word(nums) ^ string) + Literal(")"))
insertPrefix = Group(insertToken + intoToken + ident + Literal("(") + delimitedList(ident) + Literal(")") + valuesToken)
insertStmt = insertPrefix + delimitedList(value)
insertStmt.setParseAction(rebuild_insert)