How to use the pyparsing.Optional function in pyparsing

To help you get started, we’ve selected a few pyparsing examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jperon / gabctk / abc2xml / abc2xml.py View on Github external
decorations     = OneOrMore (decoration)

    tie = oneOf ('.- -')
    rest = Optional (accidental) + rest_sym + note_length
    pitch = Optional (accidental) + basenote + Optional (octave, 0)
    note = pitch + note_length + Optional (tie) + Optional (slur_ends)
    chord_note = note | decorations | rest | b1
    grace_notes = Forward ()
    chord = Suppress ('[') + OneOrMore (chord_note | grace_notes) + Suppress (']') + note_length + Optional (tie) + Optional (slur_ends)
    stem = note | chord | rest

    broken = Combine (OneOrMore ('<') | OneOrMore ('>'))

    tuplet_num   = Suppress ('(') + number
    tuplet_into  = Suppress (':') + Optional (number, 0)
    tuplet_notes = Suppress (':') + Optional (number, 0)
    tuplet_start = tuplet_num + Optional (tuplet_into + Optional (tuplet_notes))

    acciaccatura    = Literal ('/')
    grace_stem      = Optional (decorations) + stem
    grace_notes     << Group (Suppress ('{') + Optional (acciaccatura) + OneOrMore (grace_stem) + Suppress ('}'))

    text_expression  = Optional (oneOf ('^ _ < > @'), '^') + Optional (CharsNotIn ('"'), "")
    chord_accidental = oneOf ('# b =')
    triad            = oneOf ('ma Maj maj M mi min m aug dim o + -')
    seventh          = oneOf ('7 ma7 Maj7 M7 maj7 mi7 m7 dim7 o7 -7 aug7 +7 m7b5 mi7b5')
    sixth            = oneOf ('6 ma6 M6 m6 mi6')
    ninth            = oneOf ('9 ma9 M9 maj9 Maj9 mi9 m9')
    elevn            = oneOf ('11 ma11 M11 maj11 Maj11 mi m11')
    suspended        = oneOf ('sus sus2 sus4')
    chord_degree     = Combine (Optional (chord_accidental) + oneOf ('2 4 5 6 7 9 11 13'))
    chord_kind       = Optional (seventh | sixth | ninth | elevn | triad, '_') + Optional (suspended)
github inveniosoftware / invenio / modules / bibfield / lib / bibfield_config_engine.py View on Github external
description = (description_body | doc_double | doc_single)\
            .setResultsName('description')

    #Producer
    producer_code = (Word(alphas, alphanums + "_")\
           + originalTextFor(nestedExpr("(", ")")))\
           .setResultsName('producer_code', listAllMatches=True)
    producer_body = (producer_code + Suppress(",") + python_allowed_expr)\
                    .setResultsName("producer_rule", listAllMatches=True)
    producer = Suppress("producer:") + INDENT + OneOrMore(producer_body) + UNDENT

    schema = (Suppress('schema:') + INDENT + dict_def + UNDENT)\
            .setParseAction(lambda toks: toks[0])\
            .setResultsName('schema')

    body = Optional(field_def) & Optional(checker) & Optional(json_extra) \
            & Optional(description) & Optional(producer) & Optional(schema)
    comment = Literal("#") + restOfLine + LineEnd()
    include = (Suppress("include") + quotedString)\
              .setResultsName("includes", listAllMatches=True)
    rule = (Optional(persistent_identifier) + Optional(inherit_from) + \
            Optional(override) + Optional(extend) +json_id + \
            Optional(Suppress(",") + aliases) + Suppress(":") + \
            INDENT + body + UNDENT)\
           .setResultsName("rules", listAllMatches=True)

    return OneOrMore(rule | include | comment.suppress())
github elfnor / generative-art-examples / eisenscript_to_xml.py View on Github external
w_mod = weight + fnum('wm')
    
    shape_words = pp.oneOf(['box', 'grid', 'sphere', 'line'], caseless=True)
    shape = pp.Combine(shape_words + pp.Optional(pp.Word(pp.alphas + ':')))

    global_md = pp.CaselessKeyword('set') + md \
                                          + fnum('global_md')

    shape_call = (pp.Optional(loop) + 
                  shape('shape')).setResultsName('bcall', listAllMatches=True)
    rule_call = (pp.ZeroOrMore(loop) + 
            rule_name('rule_name')).setResultsName('rcall', listAllMatches=True)
    call = shape_call | rule_call
    rule = pp.Group(pp.Suppress(pp.CaselessKeyword('rule')) +
                    rule_name('name') +
                    (pp.Optional(md_mod) & pp.Optional(w_mod)) +
                    pp.Suppress('{') +
                    pp.OneOrMore(call) +
                    pp.Suppress('}'))

    entry = pp.Group(pp.OneOrMore(call)).setResultsName('entry_calls', 
                                                        listAllMatches=True)
    main = pp.Group(pp.OneOrMore(rule)).setResultsName('rule_defs', 
                                                        listAllMatches=True)
    file_def = pp.Optional(global_md) + entry + main 
    file_def.ignore(pp.cppStyleComment)
    # more stuff to ignore
    set_words = pp.oneOf('seed maxobjects maxsize minsize background ' +
                         'colorpool translation rotation pivot scale ' +
                         'raytracer syncrandom', caseless=True)
    set_ignore = pp.CaselessKeyword('set') + set_words + pp.restOfLine
    file_def.ignore(set_ignore)
github RuleWorld / bionetgen / parsers / SBMLparser / SBMLparser / utils / util.py View on Github external
def __init__(self):
        """
        expop   :: '^'
        multop  :: '*' | '/'
        addop   :: '+' | '-'
        integer :: ['+' | '-'] '0'..'9'+
        atom    :: PI | E | real | fn '(' expr ')' | '(' expr ')'
        factor  :: atom [ expop factor ]*
        term    :: factor [ multop factor ]*
        expr    :: term [ addop term ]*
        """
        point = Literal( "." )
        e     = CaselessLiteral( "E" )
        fnumber = Combine( Word( "+-"+alphanums+"_", alphanums+"_" ) + 
                           Optional( point + Optional( Word( alphanums+"_" ) ) ) +
                           Optional( e + Word( "+-"+alphanums+"_", alphanums+"_" ) ) )
        
        ident = Word(alphas,alphanums + "_")       
        plus  = Literal( "+" )
        minus = Literal( "-" )
        mult  = Literal( "*" )
        div   = Literal( "/" )
        lpar  = Literal( "(" ).suppress()
        rpar  = Literal( ")" ).suppress()
        
        addop  = plus | minus
        multop = mult | div
        expop = Literal( "^" )
        pi    = CaselessLiteral( "PI" )
        expr = Forward()
        function = ident + lpar + expr + ZeroOrMore("," + expr) + rpar
github pyparsing / pyparsing / examples / bigquery_view_parser.py View on Github external
explicit_struct = (
            STRUCT
            + Optional(LT + delimitedList(type_name) + GT)
            + LPAR
            + Optional(delimitedList(expr + Optional(AS + identifier)))
            + RPAR
        )

        case_when = WHEN + expr.copy()("when")
        case_then = THEN + expr.copy()("then")
        case_clauses = Group(ZeroOrMore(case_when + case_then))
        case_else = ELSE + expr.copy()("else")
        case_stmt = (
            CASE
            + Optional(case_expr.copy())
            + case_clauses("case_clauses")
            + Optional(case_else)
            + END
        )("case")

        expr_term = (
            (analytic_function)("analytic_function")
            | (CAST + LPAR + expr + AS + type_name + RPAR)("cast")
            | (SAFE_CAST + LPAR + expr + AS + type_name + RPAR)("safe_cast")
            | (Optional(EXISTS) + LPAR + ungrouped_select_stmt + RPAR)("subselect")
            | (literal_value)("literal")
            | (bind_parameter)("bind_parameter")
            | (EXTRACT + LPAR + expr + FROM + expr + RPAR)("extract")
            | case_stmt
            | (datetime_operators + LPAR + expr + COMMA + interval + RPAR)(
                "date_operation"
github dputhier / pygtftk / pygtftk / utils.py View on Github external
>>> from pygtftk.utils import check_boolean_exprs
    >>> assert check_boolean_exprs('s > 1 and (s < 2 or y < 2.5)', operand=['s', 'y'])

    '''
    lparen = Literal("(")
    rparen = Literal(")")
    and_operator = CaselessLiteral("and")
    or_operator = CaselessLiteral("or")
    comparison_operator = oneOf(['==', '!=', '>', '>=', '<', '<='])
    point = Literal('.')
    exponent = CaselessLiteral('E')
    plusorminus = Literal('+') | Literal('-')
    number = Word(nums)
    integer = Combine(Optional(plusorminus) + number)
    float_nb = Combine(integer +
                       Optional(point + Optional(number)) +
                       Optional(exponent + integer))
    value = float_nb
    identifier = oneOf(operand, caseless=False)  # .setParseAction(_embed)
    group_1 = identifier + comparison_operator + value
    group_2 = value + comparison_operator + identifier
    comparison = group_1 | group_2
    boolean_expr = operatorPrecedence(comparison,
                                      [(and_operator, 2, opAssoc.LEFT),
                                       (or_operator, 2, opAssoc.LEFT)])

    boolean_expr_par = lparen + boolean_expr + rparen

    expression = Forward()
    expression << boolean_expr | boolean_expr_par

    try:
github kimgr / asn1ate / asn1ate / parser.py View on Github external
defined_type = Unique(typereference)  # todo: consider other defined types from 13.1

    # these productions are used for custom parse actions,
    # because they typically generate similar code.
    simple_type = (boolean_type | null_type | octetstring_type | characterstring_type | real_type | plain_integer_type | object_identifier_type) # + Optional(constraint)
    value_list_type = restricted_integer_type | enumerated_type

    builtin_type = tagged_type | simple_type | choice_type | sequence_type | set_type | sequenceof_type | setof_type | value_list_type | bitstring_type
    referenced_type = Unique(defined_type)  # todo: consider other ref:d types from 16.3

    type_ << ((builtin_type | referenced_type) + Optional(constraint))

    # EXT: identifier should not be Optional here,
    # but our ASN.1 interpreter supports unnamed members,
    # and we use them.
    named_type << (Optional(identifier) + type_)

    # EXT: Trailing semi-colon is not allowed by standard grammar, but our ASN.1 interpreter accepts it
    # and we happen to use it.
    type_assignment = typereference + '::=' + type_ + Suppress(Optional(';'))
    value_assignment = valuereference + type_ + '::=' + value

    assignment = type_assignment | value_assignment
    assignment_list = OneOrMore(assignment)

    assigned_identifier = Optional(object_identifier_value | defined_value)
    global_module_reference = module_reference + assigned_identifier

    symbol = Unique(reference)  # TODO: parameterized reference?
    symbol_list = Group(delimitedList(symbol))

    symbols_from_module = symbol_list + Suppress(FROM) + global_module_reference
github RuleWorld / bionetgen / parsers / SBMLparser / SBMLparser / utils / smallStructures.py View on Github external
def parseReactions(reaction):
    components = (Word(alphanums + "_") + Optional(Group('~' + Word(alphanums+"_")))
    + Optional(Group('!' + Word(alphanums+'+?'))))
    molecule = (Word(alphanums + "_")
    + Optional(Suppress('(')) + Group(components) + ZeroOrMore(Suppress(',') + Group(components))    
    +Suppress(')'))
    
    species = Group(molecule) + ZeroOrMore(Suppress('.') + Group(molecule))

    result = species.parseString(reaction).asList()
    
    return result
github pm-str / QuestBot / apps / web / conditions_parsing.py View on Github external
def __init__(self):
        """
        expop   :: '^'
        multop  :: '*' | '/'
        addop   :: '+' | '-'
        integer :: ['+' | '-'] '0'..'9'+
        atom    :: PI | E | real | fn '(' expr ')' | '(' expr ')'
        """
        point = Literal(".")
        e = CaselessLiteral("E")
        fnumber = Combine(Word("+-" + nums, nums) +
                          Optional(point + Optional(Word(nums))) +
                          Optional(e + Word("+-" + nums, nums)))
        ident = Word(alphas, alphas + nums + "_$")
        plus = Literal("+")
        minus = Literal("-")
        mult = Literal("*")
        div = Literal("/")
        lpar = Literal("(").suppress()
        rpar = Literal(")").suppress()
        addop = plus | minus
        multop = mult | div
        expop = Literal("^")
        expr = Forward()
        atom = ((Optional(oneOf("- +")) +
                 (
                     ident + lpar + expr + rpar | fnumber).setParseAction(
                     self.pushFirst))
                | Optional(oneOf("- +")) + Group(lpar + expr + rpar)
github RDFLib / rdflib / rdflib / sparql / grammar.py View on Github external
ArgList << (delimitedList(VarOrLiteral))

    # [39]  Literal  ::=  URI
    # | NumericLiteral
    # | TextLiteral

    Literal << (QuotedURI | NumericLiteral | TextLiteral)

    #[40] NumericLiteral  ::=  | 

    NumericLiteral << (_INTEGER_LITERAL_ | _FLOATING_POINT_LITERAL_)

    # [41]  TextLiteral    ::=   String  ? ( '^^' URI )?

    TextLiteral << String + Optional(_LANG_) + Optional(typ.suppress() + URI).setResultsName('Type')

    # [42]   String    ::=    | 

    # [43]  URI  ::=  QuotedURI | QName

    URI << (QuotedURI | QName)

    # [44]  QName  ::=  

    # [45]  QuotedURI  ::=  

    # [46]  CommaOpt  ::=  ','?

    # [47]       ::=   "<"  (~[">"," "])* ">"

    # [48]    ::=  ()? ":"