當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。