Python pyparsing.nestedExpr() Examples
The following are 7
code examples of pyparsing.nestedExpr().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pyparsing
, or try the search function
.
Example #1
Source File: macro_expander.py From rekall with GNU General Public License v2.0 | 6 votes |
def expression(self): expression = pyparsing.Forward() # (1 + (2 + 3)) nested_expression = pyparsing.nestedExpr( "(", ")", expression).setParseAction(self._combine_lists) # FOO(2 , 3) function_call = ( _TOKEN().setResultsName("function") + _OPEN_PARENTHESIS() + pyparsing.delimitedList( pyparsing.Combine(expression, adjacent=False, joinString=" "), delim=",").setResultsName("func_args") + _CLOSE_PARENTHESIS() ) expression << pyparsing.OneOrMore( function_call.setParseAction(self._is_known_function) | pyparsing.Group(nested_expression) | _TOKEN() | _NOT_TOKEN() ) return pyparsing.Combine(expression, adjacent=False, joinString=" ")
Example #2
Source File: pattern_parser_operators.py From errudite with GNU General Public License v2.0 | 6 votes |
def gen_set(pattern_single): pattern_set = pp.nestedExpr( opener='(', closer=')', content=pp.delimitedList(pattern_single, delim=delim)) \ .setParseAction(patternSetOp) pattern_ = pattern_single | pattern_set return pattern_ # define a function that can add *+! to the end
Example #3
Source File: api.py From gnocchi with Apache License 2.0 | 5 votes |
def OperationsSchema(v): if isinstance(v, six.text_type): try: v = pyparsing.OneOrMore( pyparsing.nestedExpr()).parseString(v).asList()[0] except pyparsing.ParseException as e: api.abort(400, {"cause": "Invalid operations", "reason": "Fail to parse the operations string", "detail": six.text_type(e)}) return voluptuous.Schema(voluptuous.Any(*OperationsSchemaBase), required=True)(v)
Example #4
Source File: formula.py From idasec with GNU Lesser General Public License v2.1 | 5 votes |
def parse_parentheses(line): try: return nestedExpr('(', ')').parseString(line).asList() except ParseException: print "Exception on line:", line
Example #5
Source File: typing.py From pytorch_geometric with MIT License | 5 votes |
def sanitize(type_repr: str): type_repr = re.sub(r'<class \'(.*)\'>', r'\1', type_repr) type_repr = type_repr.replace('typing.', '') type_repr = type_repr.replace('torch_sparse.tensor.', '') type_repr = type_repr.replace('Adj', 'Union[Tensor, SparseTensor]') # Replace `Union[..., NoneType]` by `Optional[...]`. sexp = pp.nestedExpr(opener='[', closer=']') tree = sexp.parseString(f'[{type_repr.replace(",", " ")}]').asList()[0] def union_to_optional_(tree): for i in range(len(tree)): e, n = tree[i], tree[i + 1] if i + 1 < len(tree) else [] if e == 'Union' and n[-1] == 'NoneType': tree[i] = 'Optional' tree[i + 1] = tree[i + 1][:-1] elif e == 'Union' and 'NoneType' in n: idx = n.index('NoneType') n[idx] = [n[idx - 1]] n[idx - 1] = 'Optional' elif isinstance(e, list): tree[i] = union_to_optional_(e) return tree tree = union_to_optional_(tree) type_repr = re.sub(r'\'|\"', '', str(tree)[1:-1]).replace(', [', '[') return type_repr
Example #6
Source File: parser.py From holoviews with BSD 3-Clause "New" or "Revised" License | 5 votes |
def todict(cls, parseresult, mode='parens', ns={}): """ Helper function to return dictionary given the parse results from a pyparsing.nestedExpr object (containing keywords). The ns is a dynamic namespace (typically the IPython Notebook namespace) used to update the class-level namespace. """ grouped, kwargs = [], {} tokens = cls.collect_tokens(parseresult, mode) # Group tokens without '=' and append to last token containing '=' for group in groupby(tokens, lambda el: '=' in el): (val, items) = group if val is True: grouped += list(items) if val is False: elements =list(items) # Assume anything before ) or } can be joined with commas # (e.g tuples with spaces in them) joiner=',' if any(((')' in el) or ('}' in el)) for el in elements) else '' grouped[-1] += joiner + joiner.join(elements) for keyword in grouped: # Tuple ('a', 3) becomes (,'a',3) and '(,' is never valid # Same for some of the other joining errors corrected here for (fst,snd) in [('(,', '('), ('{,', '{'), ('=,','='), (',:',':'), (':,', ':'), (',,', ','), (',.', '.')]: keyword = keyword.replace(fst, snd) try: kwargs.update(eval('dict(%s)' % keyword, dict(cls.namespace, **ns))) except: if cls.abort_on_eval_failure: raise SyntaxError("Could not evaluate keyword: %r" % keyword) msg = "Ignoring keyword pair that fails to evaluate: '%s'" parsewarning.warning(msg % keyword) return kwargs
Example #7
Source File: convert_from_mesquita.py From supervised-oie with MIT License | 5 votes |
def find_enclosed_elem(annotated_sent, start_symbol, end_symbol): """ Extract elements enclosed by some denotation. """ sexp = nestedExpr(start_symbol, end_symbol, ignoreExpr = None).parseString("{}{}{}".format(start_symbol, annotated_sent, end_symbol)).asList()[0] exps = [get_raw_sent(" ".join(ls)) for ls in sexp if isinstance(ls, list)] # Make sure there's a single predicate head return exps