当前位置: 首页>>代码示例>>Python>>正文


Python pyparsing.nestedExpr方法代码示例

本文整理汇总了Python中pyparsing.nestedExpr方法的典型用法代码示例。如果您正苦于以下问题:Python pyparsing.nestedExpr方法的具体用法?Python pyparsing.nestedExpr怎么用?Python pyparsing.nestedExpr使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyparsing的用法示例。


在下文中一共展示了pyparsing.nestedExpr方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: expression

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
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=" ") 
开发者ID:google,项目名称:rekall,代码行数:27,代码来源:macro_expander.py

示例2: OperationsSchema

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
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) 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:13,代码来源:api.py

示例3: parse_parentheses

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
def parse_parentheses(line):
    try:
        return nestedExpr('(', ')').parseString(line).asList()
    except ParseException:
        print "Exception on line:", line 
开发者ID:RobinDavid,项目名称:idasec,代码行数:7,代码来源:formula.py

示例4: sanitize

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
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 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:30,代码来源:typing.py

示例5: gen_set

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
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 
开发者ID:uwdata,项目名称:errudite,代码行数:12,代码来源:pattern_parser_operators.py

示例6: todict

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
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 
开发者ID:holoviz,项目名称:holoviews,代码行数:43,代码来源:parser.py

示例7: find_enclosed_elem

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import nestedExpr [as 别名]
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 
开发者ID:gabrielStanovsky,项目名称:supervised-oie,代码行数:17,代码来源:convert_from_mesquita.py


注:本文中的pyparsing.nestedExpr方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。