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


Python pyparsing.Optional方法代码示例

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


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

示例1: _maybe_attributes

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def _maybe_attributes(self):
        """Possibly match some attributes.

        The syntax of attributes is described here:
        https://gcc.gnu.org/onlinedocs/gcc/Attribute-Syntax.html
        """
        return pyparsing.Group(
            pyparsing.ZeroOrMore(
                _ATTRIBUTE
                + _DOUBLE_OPEN_PARENTHESIS
                + pyparsing.delimitedList(
                    pyparsing.Group(
                        self._identifier()("name")
                        + pyparsing.Optional(
                            _OPEN_PARENTHESIS
                            + parsers.anything_beetween("()")("args")
                            + _CLOSE_PARENTHESIS
                        )
                    )
                )
                + _DOUBLE_CLOSE_PARENTHESIS
            ).setParseAction(self._make_attribute)
        )("attributes") 
开发者ID:google,项目名称:rekall,代码行数:25,代码来源:c_parser.py

示例2: _globalParse___username_attributes

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def _globalParse___username_attributes(line):
    username_dict = {}

    username       = (Word(printables))                                         ('user')
    privilege      = (Suppress('privilege') + Word(nums))                       ('priv_num')
    password_type  = (Suppress(MatchFirst(['secret', 'password'])) + Word(nums))('pass_type')

    parse_username = username + Optional(privilege) + password_type + Suppress(restOfLine)

    result = parse_username.parseString(line)

    username_dict[result.user] = {}
    username_dict[result.user]['password_type'] = result.pass_type.asList()[0]

    try:
        username_dict[result.user]['privilege'] = result.priv_num.asList()[0]
    except AttributeError:
        pass

    return username_dict 
开发者ID:cisco-config-analysis-tool,项目名称:ccat,代码行数:22,代码来源:username.py

示例3: __ifaceAttributes___storm_check

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def __ifaceAttributes___storm_check(storm,dct):

    parse_level  = Word(alphas)        + Suppress('level ')            + restOfLine
    parse_action = Suppress('action ') + Word(alphas)
    parse_type   = Word(alphas)        + Suppress(Optional("include")) + Word(alphas)
    try:
        value = parse_level.parseString(storm).asList()
        if 'level' in dct:
            dct['level'].append(value)
        else:
            dct['level'] = [value]
        return dct
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_action, storm, 'action', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_type,   storm, 'type',   dct)
    except ParseException:
        pass 
开发者ID:cisco-config-analysis-tool,项目名称:ccat,代码行数:24,代码来源:storm_control.py

示例4: get_protein_modification_language

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def get_protein_modification_language(concept_qualified: ParserElement) -> ParserElement:
    """Build a protein modification parser."""
    pmod_concept = MatchFirst([
        concept_qualified,
        pmod_default_ns,
        pmod_legacy_ns,
    ])

    return pmod_tag + nest(
        Group(pmod_concept)(CONCEPT)
        + Optional(
            WCW
            + amino_acid(PMOD_CODE)
            + Optional(WCW + ppc.integer(PMOD_POSITION)),
        ),
    ) 
开发者ID:pybel,项目名称:pybel,代码行数:18,代码来源:protein_modification.py

示例5: parse

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def parse(input_string):
        word = Word(alphanums)
        command = Group(OneOrMore(word))
        token = Suppress("->")
        device = Group(OneOrMore(word))
        argument = Group(OneOrMore(word))
        event = command + token + device + Optional(token + argument)
        parse_results = event.parseString(input_string)
        cmd = parse_results[0]
        dev = parse_results[1]
        cmd_str = "_".join(cmd)
        dev_str = "_".join(dev)
        try:
            val = parse_results[2]
        except IndexError:
            val_str = None
        else:
            val_str = "_".join(val)
        return cmd_str, dev_str, val_str 
开发者ID:jackdbd,项目名称:design-patterns,代码行数:21,代码来源:interpreter.py

示例6: __init__

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def __init__(
        self,
        element: pyparsing.ParserElement,
        converted: EditablePartial,
        parent: EditablePartial,
        number: int,
        name: str = None,
        index: Optional[int] = None,
    ):
        #: The pyparsing element that this represents
        self.element = element  # type: pyparsing.ParserElement
        #: The name of the element
        self.name = name  # type: str
        #: The output Railroad element in an unconverted state
        self.converted = converted  # type: EditablePartial
        #: The parent Railroad element, which we store so that we can extract this if it's duplicated
        self.parent = parent  # type: EditablePartial
        #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
        self.number = number  # type: int
        #: The index of this inside its parent
        self.parent_index = index  # type: Optional[int]
        #: If true, we should extract this out into a subdiagram
        self.extract = False  # type: bool
        #: If true, all of this element's chilren have been filled out
        self.complete = False  # type: bool 
开发者ID:pyparsing,项目名称:pyparsing,代码行数:27,代码来源:__init__.py

示例7: tableValue

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def tableValue(expr, colstart, colend):
    empty_cell_is_zero = False
    if empty_cell_is_zero:
        return Optional(
            expr.copy().addCondition(
                mustMatchCols(colstart, colend), message="text not in expected columns"
            ),
            default=0,
        )
    else:
        return Optional(
            expr.copy().addCondition(
                mustMatchCols(colstart, colend), message="text not in expected columns"
            )
        )


# define the grammar for this simple table 
开发者ID:pyparsing,项目名称:pyparsing,代码行数:20,代码来源:parseTabularData.py

示例8: grammar

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def grammar():
    parenthesis = Forward()
    parenthesis <<= "(" + ZeroOrMore(CharsNotIn("()") | parenthesis) + ")"

    field_def = OneOrMore(Word(alphanums + "_\"'`:-") | parenthesis)
    field_def.setParseAction(field_act)

    tablename_def = ( Word(alphas + "`_") | QuotedString("\"") )

    field_list_def = field_def + ZeroOrMore(Suppress(",") + field_def)
    field_list_def.setParseAction(field_list_act)

    create_table_def = Literal("CREATE") + "TABLE" + tablename_def.setResultsName("tableName") + "(" + field_list_def.setResultsName("fields") + ")" + ";"
    create_table_def.setParseAction(create_table_act)

    add_fkey_def = Literal("FOREIGN") + "KEY" + "(" + Word(alphanums).setResultsName("keyName") + ")" + "REFERENCES" + Word(alphanums).setResultsName("fkTable") + "(" + Word(alphanums + "_").setResultsName("fkCol") + ")" + Optional(Literal("DEFERRABLE")) + ";"
    add_fkey_def.setParseAction(add_fkey_act)

    other_statement_def = OneOrMore(CharsNotIn(";")) + ";"
    other_statement_def.setParseAction(other_statement_act)

    comment_def = "--" + ZeroOrMore(CharsNotIn("\n"))
    comment_def.setParseAction(other_statement_act)

    return OneOrMore(comment_def | create_table_def | add_fkey_def | other_statement_def) 
开发者ID:LGE-ARC-AdvancedAI,项目名称:auptimizer,代码行数:27,代码来源:sql_graphviz.py

示例9: _apply_modifiers

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def _apply_modifiers(rule, modifiers):
        if 'grouped' in modifiers:
            rule = pp.Group(rule)

        if 'optional' in modifiers:
            rule = pp.Optional(rule)
        else:
            for modifier in modifiers:
                if modifier.startswith('at_least'):
                    times = rule_at_least.parseString(modifier)[0]
                    if times > 0:
                        rule_multiple = rule
                        for _ in range(1, times):
                            rule_multiple = rule_multiple + rule
                        rule = rule_multiple + pp.ZeroOrMore(rule)
                    else:
                        rule = pp.Optional(pp.ZeroOrMore(rule))

        return rule 
开发者ID:weso,项目名称:CWR-DataApi,代码行数:21,代码来源:rule.py

示例10: ResourceSchema

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def ResourceSchema(schema):
    base_schema = {
        voluptuous.Optional('started_at'): utils.to_datetime,
        voluptuous.Optional('ended_at'): utils.to_datetime,
        voluptuous.Optional('user_id'): voluptuous.Any(None, six.text_type),
        voluptuous.Optional('project_id'): voluptuous.Any(None, six.text_type),
        voluptuous.Optional('metrics'): MetricsSchema,
    }
    base_schema.update(schema)
    return base_schema 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:12,代码来源:api.py

示例11: BackwardCompatibleMeasuresList

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def BackwardCompatibleMeasuresList(v):
        v = voluptuous.Schema(
            voluptuous.Any(MeasuresListSchema,
                           {voluptuous.Optional("archive_policy_name"):
                            six.text_type,
                            voluptuous.Optional("unit"):
                            six.text_type,
                            "measures": MeasuresListSchema}),
            required=True)(v)
        if isinstance(v, dict):
            return v
        else:
            # Old format
            return {"measures": v} 
开发者ID:gnocchixyz,项目名称:gnocchi,代码行数:16,代码来源:api.py

示例12: _make_matcher_element

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def _make_matcher_element(self):
        return self._set_matcher_element_attributes(
            pyparsing.Optional(self.child.matcher_element)
        ) 
开发者ID:Danesprite,项目名称:pyjsgf,代码行数:6,代码来源:expansions.py

示例13: parse_line

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def parse_line(attribute, string):

    Grammar = Suppress(Keyword('mpc.{}'.format(attribute)) + Keyword('=')) + String('data') + Suppress(Literal(';') + Optional(Comments))
    result, i, j = Grammar.scanString(string).next()

    return [int_else_float_except_string(s) for s in result['data'].asList()] 
开发者ID:power-system-simulation-toolbox,项目名称:psst,代码行数:8,代码来源:case_parser.py

示例14: parse_table

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def parse_table(attribute, string):
    Line = OneOrMore(Float)('data') + Literal(';') + Optional(Comments, default='')('name')
    Grammar = Suppress(Keyword('mpc.{}'.format(attribute)) + Keyword('=') + Keyword('[') + Optional(Comments)) + OneOrMore(Group(Line)) + Suppress(Keyword(']') + Optional(Comments))

    result, i, j = Grammar.scanString(string).next()

    _list = list()
    for r in result:
        _list.append([int_else_float_except_string(s) for s in r['data'].asList()])

    return _list 
开发者ID:power-system-simulation-toolbox,项目名称:psst,代码行数:13,代码来源:case_parser.py

示例15: _define_function_like

# 需要导入模块: import pyparsing [as 别名]
# 或者: from pyparsing import Optional [as 别名]
def _define_function_like(self):
        return (
            (_IDENTIFIER.setResultsName("name")
             + _OPEN_PARENTHESES).leaveWhitespace()
            + pyparsing.Optional(
                pyparsing.delimitedList(
                    _IDENTIFIER
                    | pyparsing.Literal("...")  # vararg macro.
                )).setResultsName("arguments")
            + _CLOSE_PARENTHESES
            + pyparsing.restOfLine.setResultsName("replacement")
        ).setParseAction(self._add_function_like) 
开发者ID:google,项目名称:rekall,代码行数:14,代码来源:preprocessing_parser.py


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