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


Python Literal.suppress方法代码示例

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


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

示例1: parser

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        
        lbrack = Literal("[")
        rbrack = Literal("]")
        lbrace = Literal("{")
        rbrace = Literal("}")
        lparen = Literal("(")
        rparen = Literal(")")
        
        reMacro = Suppress("\\") + oneOf(list("dwsZ"))
        escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
        reLiteralChar = "".join(c for c in string.printable if c not in r"\[]{}().*?+|")

        reRange = Combine(lbrack.suppress() + SkipTo(rbrack,ignore=escapedChar) + rbrack.suppress())
        reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
        reDot = Literal(".")
        repetition = (
            ( lbrace + Word(nums).setResultsName("count") + rbrace ) |
            ( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
            oneOf(list("*+?"))
            )
        reExpr = Forward()
        reGroup = (lparen.suppress() +
                   Optional(Literal("?").suppress() + oneOf(list(":P"))).setResultsName("option") +
                   reExpr.setResultsName("expr") +
                   rparen.suppress())

        reTerm = ( reLiteral | reRange | reMacro | reDot | reGroup )
        reExpr << operatorPrecedence( reTerm,
            [
            (repetition, 1, opAssoc.LEFT, create(Repetition)),
            (None, 2, opAssoc.LEFT, create(Sequence)),
            (Suppress('|'), 2, opAssoc.LEFT, create(Alternation)),
            ]
            )

        reGroup.setParseAction(create(Group))
        reRange.setParseAction(create(Range))
        reLiteral.setParseAction(create(Character))
        reMacro.setParseAction(create(Macro))
        reDot.setParseAction(create(Dot))
        
        _parser = reExpr
        
    return _parser
开发者ID:GunioRobot,项目名称:pycucumber,代码行数:50,代码来源:regex_parser.py

示例2: __init__

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
    def __init__(self):
        from pyparsing import (ParserElement, StringEnd, LineEnd, Literal,
                               pythonStyleComment, ZeroOrMore, Suppress,
                               Optional, Combine, OneOrMore, Regex, oneOf,
                               QuotedString, Group, ParseException)

        ParserElement.setDefaultWhitespaceChars("\t ")

        EOF = StringEnd()
        EOL = ~EOF + LineEnd() # EOL must not match on EOF

        escape = Literal("\\")
        comment = pythonStyleComment
        junk = ZeroOrMore(comment | EOL).suppress()

        ## word (i.e: single argument string)
        word = Suppress(escape + EOL + Optional(comment)) \
        | Combine(OneOrMore( escape.suppress() + Regex(".") |
                             QuotedString("'", escChar='\\', multiline=True) |
                             QuotedString('"', escChar='\\', multiline=True) |
                             Regex("[^ \t\r\n\f\v\\\\$&<>();\|\'\"`]+") |
                             Suppress(escape + EOL) ))

        ## redirector (aka bash file redirectors, such as "2>&1" sequences)
        fd_src = Regex("[0-2]").setParseAction(lambda t: int(t[0]))
        fd_dst = Suppress("&") + fd_src
        # "[n]<word" || "[n]<&word" || "[n]<&digit-"
        fd_redir = (Optional(fd_src, 0) + Literal("<")
                    |Optional(fd_src, 1) + Literal(">"))\
                   +(word | (fd_dst + Optional("-")))
        # "&>word" || ">&word"
        full_redir = (oneOf("&> >&") + word)\
                     .setParseAction(lambda t:("&" ,">", t[-1]))
        # "<<<word" || "<<[-]word"
        here_doc = Regex("<<(<|-?)") + word
        # "[n]>>word"
        add_to_file = Optional(fd_src | Literal("&"), 1) + \
                      Literal(">>") + word
        # "[n]<>word"
        fd_bind = Optional(fd_src, 0) + Literal("<>") + word

        redirector = (fd_redir | full_redir | here_doc
                      | add_to_file | fd_bind)\
                     .setParseAction(lambda token: tuple(token))

        ## single command (args/redir list)
        command = Group(OneOrMore(redirector | word))

        ## logical operators (section splits)
        semicolon = Suppress(";") + junk
        connector = (oneOf("&& || |") + junk) | semicolon

        ## pipeline, aka logical block of interconnected commands
        pipeline = junk + Group(command +
                                ZeroOrMore(connector + command) +
                                Optional(semicolon))

        # define object attributes
        self.LEXER = pipeline.ignore(comment) + EOF
        self.parseException = ParseException
开发者ID:0x0mar,项目名称:phpsploit,代码行数:62,代码来源:lexer.py

示例3: __init__

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
    def __init__(self):
        left_bracket = Literal("{").suppress()
        right_bracket = Literal("}").suppress()
        semicolon = Literal(";").suppress()
        space = White().suppress()
        key = Word(alphanums + "+.-_/")
        value = ZeroOrMore(
            CharsNotIn('{};#"\'') | space |
            QuotedString("'", escChar='\\', multiline=True) |
            QuotedString('"', escChar='\\', multiline=True))
        # modifier for location uri [ = | ~ | ~* | ^~ ]
        modifier = Literal("=") | Literal("~*") | Literal("~") | Literal("^~")

        comment = Literal('#').suppress() + Optional(restOfLine)

        # rules
        assignment = Group(
            (key | value) + value + semicolon +
            Optional(space + comment))
        block = Forward()

        block << Group(
            Group(key + Optional(space + modifier) + Optional(space) +
                  Optional(value) + Optional(space + value)) +
            left_bracket +
            Group(ZeroOrMore(assignment | block | comment.suppress())) +
            right_bracket)

        def comment_handler(t):
            result = []

            if "promo" in t[0]:
                result.append("promo")
            if "author: " in t[0]:
                try:
                    email = t[0].split("author: ")[1].strip()
                    result.append(email)
                except Exception:
                    result.append(t[0])
            return result

        comment.setParseAction(comment_handler)

        self.script = OneOrMore(assignment | block | comment.suppress())
开发者ID:m-messiah,项目名称:distributor,代码行数:46,代码来源:__init__.py

示例4: _get_handbrake_title_pattern

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
    def _get_handbrake_title_pattern(self):
        title = Literal("+ title").suppress()
        integer = Word("0123456789")
        time = Combine(integer + ":" + integer + ":" + integer)
        duration = Literal("+ duration:").suppress()
        subtitle = Literal("+ subtitle tracks:")
        iso = Literal('(iso639-2:').suppress() + Word(alphas)
        subtitle_track = Literal("+").suppress() + Group(integer + SkipTo(iso).suppress() + iso) + restOfLine.suppress()

        title_num = integer.setResultsName("title")
        duration_num = time.setResultsName("duration")
        subtitles = Group(ZeroOrMore(subtitle_track)).setResultsName("subtitles")

        pattern = title + title_num + \
            SkipTo(duration).suppress() + \
            duration + duration_num + \
            SkipTo(subtitle).suppress() + subtitle.suppress() + subtitles
            
        return pattern
开发者ID:jeffreyparker,项目名称:brakejob,代码行数:21,代码来源:brakejob.py

示例5: remove_comments

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
def remove_comments(string):
    """Remove comments from the statements

    Args:
        string(str): String to be processed

    Returns:
        result(str): String with comments trimmed
    """

    if string == '':
        return string

    # Remove multiline comments
    multiline_comment = nestedExpr('/*', '*/').suppress()
    string = multiline_comment.transformString(string)

    # Remove single line comments
    singleline_comment = Literal('--') + ZeroOrMore(CharsNotIn('\n'))
    string = singleline_comment.suppress().transformString(string)

    return string
开发者ID:abhishekmahawar,项目名称:dataduct,代码行数:24,代码来源:transform.py

示例6: Word

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
    Word(srange("[A-Z]") + srange("[a-z]")) + restOfLine) + gEOL_keep
#gText = OneOrMore(gShortText)
#gIntroduction = Optional(
    #Group(Word(srange("[A-Z]") + srange("[a-z]")) + Regex(".*:$"))
    #.setResultsName("introduction"))
gOptionDescriptionText = \
    Optional(gRepetition + Literal(':')) + \
    OneOrMore(
        Optional(Regex("\n")) + gSpaces + Optional(Literal('(')) +
        Word(alphas, alphanums + '_') + restOfLine)\
    .setResultsName("description")
gOptionDescriptionOption = gSpaces + \
    gRawOption.setResultsName("first_option") + Optional(gParameter) + \
    ZeroOrMore(
        Group(
            Literal(",").suppress() + gSpace.suppress() +
            gRawOption.setResultsName("option") + Optional(gParameter)))\
    .setResultsName("other_options")
gOptionDescriptionSwitch = Or([
    gOptionDescriptionOption,
    gInnerParameter,
    gStdin])
gOptionDescription = (gOptionDescriptionSwitch + gOptionDescriptionText)\
    .setResultsName("option_description")
#gBidule = gIntroduction + gOptionDescription
#gSubNext = Or([gBidule, gShortText.setResultsName("short_text")])
#gNext = Dict(ZeroOrMore(Group(gSubNext))).setResultsName("next")
gRest = Regex("(.*\n?)*").setResultsName("rest")
gHelp = Optional(gEmptyLine) + gUsage + gRest

开发者ID:dchilot,项目名称:viscum,代码行数:31,代码来源:laxum.py

示例7: _create_field_parser

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
def _create_field_parser():
    """
    Creates a parser using pyparsing that works with bibfield rule definitions

    BNF like grammar:

    rule ::= ([persitent_identifier] json_id ["[0]" | "[n]"] "," aliases":" INDENT body UNDENT) | include | python_comment
    include ::= "include(" PATH ")"
    body ::=  [inherit_from] (creator | derived | calculated) [checker] [documentation] [producer]
    aliases ::= json_id ["[0]" | "[n]"] ["," aliases]

    creator ::= "creator:" INDENT creator_body+ UNDENT
    creator_body ::= [decorators] source_format "," source_tag "," python_allowed_expr
    source_format ::= MASTER_FORMATS
    source_tag ::= QUOTED_STRING

    derived ::= "derived" INDENT derived_calculated_body UNDENT
    calculated ::= "calculated:" INDENT derived_calculated_body UNDENT
    derived_calculated_body ::= [decorators] "," python_allowed_exp

    decorators ::= (peristent_identfier | legacy | do_not_cache | parse_first | depends_on | only_if | only_if_master_value)*
    peristent_identfier ::= @persitent_identifier( level )
    legacy ::= "@legacy(" correspondences+ ")"
    correspondences ::= "(" source_tag [ "," tag_name ] "," json_id ")"
    parse_first ::= "@parse_first(" jsonid+ ")"
    depends_on ::= "@depends_on(" json_id+ ")"
    only_if ::= "@only_if(" python_condition+ ")"
    only_if_master_value ::= "@only_if_master_value(" python_condition+  ")"

    inherit_from ::= "@inherit_from()"

    python_allowed_exp ::= ident | list_def | dict_def | list_access | dict_access | function_call

    checker ::= "checker:" INDENT checker_function+ UNDENT

    documentation ::= INDENT doc_string subfield* UNDENT
    doc_string ::= QUOTED_STRING
    subfield ::= "@subfield" json_id["."json_id*] ":" docstring

    producer ::= "producer:" INDENT producer_body UNDENT
    producer_body ::= producer_code "," python_dictionary
    producer_code ::= ident
    """

    indent_stack = [1]

    def check_sub_indent(str, location, tokens):
        cur_col = col(location, str)
        if cur_col > indent_stack[-1]:
            indent_stack.append(cur_col)
        else:
            raise ParseException(str, location, "not a subentry")

    def check_unindent(str, location, tokens):
        if location >= len(str):
            return
        cur_col = col(location, str)
        if not(cur_col < indent_stack[-1] and cur_col <= indent_stack[-2]):
            raise ParseException(str, location, "not an unindent")

    def do_unindent():
        indent_stack.pop()

    INDENT = lineEnd.suppress() + empty + empty.copy().setParseAction(check_sub_indent)
    UNDENT = FollowedBy(empty).setParseAction(check_unindent)
    UNDENT.setParseAction(do_unindent)

    json_id = (Word(alphas + "_", alphanums + "_") + Optional(oneOf("[0] [n]")))\
              .setResultsName("json_id", listAllMatches=True)\
              .setParseAction(lambda tokens: "".join(tokens))
    aliases = delimitedList((Word(alphanums + "_") + Optional(oneOf("[0] [n]")))
                            .setParseAction(lambda tokens: "".join(tokens)))\
              .setResultsName("aliases")
    ident = Word(alphas + "_", alphanums + "_")
    dict_def = originalTextFor(nestedExpr('{', '}'))
    list_def = originalTextFor(nestedExpr('[', ']'))
    dict_access = list_access = originalTextFor(ident + nestedExpr('[', ']'))
    function_call = originalTextFor(ZeroOrMore(ident + ".") + ident + nestedExpr('(', ')'))

    python_allowed_expr = (dict_def ^ list_def ^ dict_access ^ \
            list_access ^ function_call ^ restOfLine)\
            .setResultsName("value", listAllMatches=True)

    persistent_identifier = (Suppress("@persistent_identifier") + \
            nestedExpr("(", ")"))\
            .setResultsName("persistent_identifier")
    legacy = (Suppress("@legacy") + originalTextFor(nestedExpr("(", ")")))\
            .setResultsName("legacy", listAllMatches=True)
    only_if = (Suppress("@only_if") + originalTextFor(nestedExpr("(", ")")))\
            .setResultsName("only_if")
    only_if_master_value = (Suppress("@only_if_value") + \
            originalTextFor(nestedExpr("(", ")")))\
            .setResultsName("only_if_master_value")
    depends_on = (Suppress("@depends_on") + \
            originalTextFor(nestedExpr("(", ")")))\
            .setResultsName("depends_on")
    parse_first = (Suppress("@parse_first") + \
            originalTextFor(nestedExpr("(", ")")))\
            .setResultsName("parse_first")
    memoize = (Suppress("@memoize") + nestedExpr("(", ")"))\
#.........这里部分代码省略.........
开发者ID:aw-bib,项目名称:tind-invenio,代码行数:103,代码来源:bibfield_config_engine.py

示例8: graph_definition

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
def graph_definition():
	global graphparser
	
	if not graphparser:
		# punctuation
		colon  = Literal(":")
		lbrace = Literal("{")
		rbrace = Literal("}")
		lbrack = Literal("[")
		rbrack = Literal("]")
		lparen = Literal("(")
		rparen = Literal(")")
		equals = Literal("=")
		comma  = Literal(",")
		dot    = Literal(".")
		slash  = Literal("/")
		bslash = Literal("\\")
		star   = Literal("*")
		semi   = Literal(";")
		at     = Literal("@")
		minus  = Literal("-")
		
		# keywords
		strict_    = Literal("strict")
		graph_     = Literal("graph")
		digraph_   = Literal("digraph")
		subgraph_  = Literal("subgraph")
		node_      = Literal("node")
		edge_      = Literal("edge")

		
		# token definitions
		
		identifier = Word(alphanums + "_" ).setName("identifier")
		
 		double_quoted_string = dblQuotedString

		alphastring_ = OneOrMore(CharsNotIn(_noncomma))

		ID = (identifier | double_quoted_string.setParseAction(strip_quotes) |\
			alphastring_).setName("ID")
			
		html_text = Combine(Literal("<<") + OneOrMore(CharsNotIn(",]")))
		
		float_number = Combine(Optional(minus) +	\
			OneOrMore(Word(nums + "."))).setName("float_number")
			
		righthand_id =  (float_number | ID | html_text).setName("righthand_id")

		port_angle = (at + ID).setName("port_angle")
		
		port_location = (Group(colon + ID) |	\
			Group(colon + lparen + ID + comma + ID + rparen)).setName("port_location")
			
		port = (Group(port_location + Optional(port_angle)) |	\
			Group(port_angle + Optional(port_location))).setName("port")
			
		node_id = (ID + Optional(port))
		a_list = OneOrMore(ID + Optional(equals.suppress() + righthand_id) +	\
			Optional(comma.suppress())).setName("a_list")
			
		attr_list = OneOrMore(lbrack.suppress() + Optional(a_list) +	\
			rbrack.suppress()).setName("attr_list")
			
		attr_stmt = (Group(graph_ | node_ | edge_) + attr_list).setName("attr_stmt")

		edgeop = (Literal("--") | Literal("->")).setName("edgeop")

		stmt_list = Forward()
		graph_stmt = Group(lbrace.suppress() + Optional(stmt_list) +	\
			rbrace.suppress()).setName("graph_stmt")
			
		subgraph = (Group(Optional(subgraph_ + Optional(ID)) + graph_stmt) |	\
			Group(subgraph_ + ID)).setName("subgraph")
			
		edgeRHS = OneOrMore(edgeop + Group(node_id | subgraph))
		
		edge_stmt = Group(node_id | subgraph) + edgeRHS + Optional(attr_list)

		node_stmt = (node_id + Optional(attr_list) + Optional(semi.suppress())).setName("node_stmt")
		
		assignment = (ID + equals.suppress() + righthand_id).setName("assignment")
		stmt =  (assignment | edge_stmt | attr_stmt | subgraph | node_stmt).setName("stmt")
		stmt_list << OneOrMore(stmt + Optional(semi.suppress()))

		graphparser = (Optional(strict_) + Group((graph_ | digraph_)) +	\
			Optional(ID) + graph_stmt).setResultsName("graph")

		singleLineComment = "//" + restOfLine
		
		
		# actions
		
		graphparser.ignore(singleLineComment)
		graphparser.ignore(cStyleComment)

		assignment.setParseAction(push_attr_list)
		a_list.setParseAction(push_attr_list)
		edge_stmt.setParseAction(push_edge_stmt)
		node_stmt.setParseAction(push_node_stmt)
#.........这里部分代码省略.........
开发者ID:hristozov,项目名称:Yogi,代码行数:103,代码来源:dot_parser.py

示例9: Combine

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
float_number = Combine( integer +
                        Optional( point + Optional(number) )
                        ).setParseAction(lambda t:float(t[0]))

# (originally I had pyparsing pulling out the $(Macro) references from inside names
# as well, but the framework doesn't work especially well without whitespace delimiters between
# tokens so we just do simple find/replace in a second pass
pv_name = Word(alphanums+":._$()")

pv_value = (float_number | Word(alphanums))
pv_assignment = pv_name + pv_value

comment = Literal("#") + Regex(r".*")

macro = Group( Word(alphas) + Literal("=").suppress() + pv_name )
macros = Optional(macro + ZeroOrMore(Word(";,").suppress() + macro) )

#file_include = Literal("file") + pv_name + macros
file_include = Literal("file") + \
               (file_name | ignored_quote + file_name + ignored_quote) \
               + Optional(ignored_comma) + macros

def line(contents):
    return LineStart() + ZeroOrMore(Group(contents)) + LineEnd().suppress()

req_line = line( file_include | comment.suppress() | pv_name )
req_file = OneOrMore(req_line) + StringEnd().suppress()

sav_line = line( comment.suppress() | Literal("<END>").suppress() | pv_assignment)
sav_file = OneOrMore(sav_line) + StringEnd().suppress()
开发者ID:NSLS-II-CSX,项目名称:pyepics,代码行数:32,代码来源:save_restore.py

示例10: Combine

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
sglQuotedString = Combine( _sglQuote + ZeroOrMore( CharsNotIn("\\'\n\r") | _escapedChar | "''" ) + _sglQuote ).streamline().setName("string enclosed in single quotes")
quotedArg = ( dblQuotedString | sglQuotedString )
quotedArg.setParseAction(removeQuotes)
quotedArg.setName("quotedArg")

plainArgChars = printables.replace('#', '').replace('"', '').replace("'", "")
plainArg = Word(plainArgChars)
plainArg.setName("plainArg")

arguments = Group(ZeroOrMore(quotedArg | plainArg))
arguments = arguments.setResultsName('arguments')
arguments.setName("arguments")

# comment line.
comment = Literal('#') + restOfLine
comment = comment.suppress()
comment.setName('comment')

full_command = (
    comment
    | (command + arguments + Optional(comment))
    )
full_command.setName('full_command')

###

command_list = []           # filled in by namespaces.init_global_dict().

### command/argument handling.

def process_args(args, globals_dict, locals_dict):
开发者ID:marcosptf,项目名称:fedora,代码行数:33,代码来源:parse.py

示例11: Word

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
#
nameType = Word(alphanums+"@_:|")

real    = Combine(Word(nums+"+-", nums) + Optional(dot) + Optional(Word(nums)) + Optional(CaselessLiteral("E") + Word(nums+"+-",nums))).setParseAction(to_float)
integer = Word(nums+"+-", nums).setParseAction(to_int)
number  = integer ^ real

number_range = Group(number + minus + number).setParseAction(to_list)

color  = Color  + lparen + Group(delimitedList(number)).setParseAction(to_list) + rparen + Optional(aster + number)
acolor = AColor + lparen + Group(delimitedList(number)).setParseAction(to_list) + rparen
vector = Vector + lparen + Group(delimitedList(number)).setParseAction(to_list) + rparen

matrix    = Matrix + lparen + Group(delimitedList(vector)).setParseAction(to_list) + rparen

transform = Transform + lparen + Group(matrix + comma.suppress() + vector).setParseAction(to_list) + rparen
transformHex = TransformHex  + lparen + quotedString.setParseAction(no_quotes) + rparen
tm = transform ^ transformHex

listStr    = List      + lparen + Group(Optional(delimitedList(nameType ^ acolor ^ integer ^ number))).setParseAction(to_list) + rparen
listInt    = ListInt   + lparen + Group(Optional(delimitedList(integer))).setParseAction(to_list)            + rparen
listFloat  = ListFloat + lparen + Group(delimitedList(number)).setParseAction(to_list)             + rparen
listVector = ListVector + lparen + Group(delimitedList(vector)).setParseAction(to_list) + rparen
listString = ListString + lparen + Group(quotedString.setParseAction(no_quotes)).setParseAction(to_list) + rparen

listIntHex    = ListIntHex    + lparen + quotedString.setParseAction(no_quotes) + rparen
listFloatHex  = ListFloatHex  + lparen + quotedString.setParseAction(no_quotes) + rparen
listVectorHex = ListVectorHex + lparen + quotedString.setParseAction(no_quotes) + rparen
listColorHex  = ListColorHex  + lparen + quotedString.setParseAction(no_quotes) + rparen

vectorList = listVector ^ listVectorHex
开发者ID:bdancer,项目名称:vray_tools,代码行数:33,代码来源:VRaySceneParser.py

示例12: Literal

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
true = Literal("True")
false = Literal("False")
atom = Forward()
infix = infixNotation(atom,
    [
    ('not', 1, opAssoc.RIGHT, _make_unary),
    (oneOf('* /'), 2, opAssoc.LEFT, _make_binary),
    (oneOf('+ -'), 2, opAssoc.LEFT, _make_binary),
    (oneOf('> gt >= ge < lt <= le != ne == eq'),
        2, opAssoc.LEFT, _make_binary),
    ('and', 2, opAssoc.LEFT, _make_binary),
    ('or', 2, opAssoc.LEFT, _make_binary),
    ('in', 2, opAssoc.LEFT, _make_binary),
    ])
dellist = delimitedList(Optional(atom))
listing = lbr.suppress() + dellist + rbr.suppress()
function = identifier.setResultsName('name') + lpar.suppress() + Group(
        Optional(delimitedList(atom))).setResultsName("args") + rpar.suppress()
atom << (listing | number | string | variable | true | false | none | function)

_false = Const(False)
_true = Const(True)

number.setParseAction(lambda t: Const(_number(t[0])))
variable.setParseAction(lambda t: Variable(t[0].strip("$")))
string.setParseAction(lambda t: Const(_str(t[0])))
none.setParseAction(lambda t: _false)
false.setParseAction(lambda t: _false)
true.setParseAction(lambda t: _true)
dellist.setParseAction(lambda s, l, t: List(t[:]))
function.setParseAction(_make_func)
开发者ID:ringo-framework,项目名称:brabbel,代码行数:33,代码来源:parser.py

示例13: ObfuscateBNF

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
class ObfuscateBNF(object):
    __metaclass__ = abc.ABCMeta

    def __init__(self, get_obfuscated):
        """BNF grammar for source statements.

        Parameters
        ----------
        get_obfuscated : function
            Function to return the obfuscated name for an identifier.
        """
        self.get_obfuscated = get_obfuscated

        self.directive = oneOf("#:")
        self.comment = ~self.directive + pythonStyleComment

        self.separator = Word("[email protected]$%^&*()+`-={}|[]:;<>?,/.", max=2)

        self.string = \
            QuotedString(quoteChar='"', escChar='\\', multiline=False,
                         unquoteResults=False) |\
            QuotedString(quoteChar="'", escChar='\\', multiline=False,
                         unquoteResults=False)

        self.doc_string = \
            QuotedString(quoteChar='"""', escChar='\\', multiline=True,
                         unquoteResults=False) |\
            QuotedString(quoteChar="'''", escChar='\\', multiline=True,
                         unquoteResults=False)
        self.string_or_doc = self.doc_string | self.string
        self.triple_quote = Literal("'''") | Literal('"""')

        self.e = Literal('E') | Literal('e')
        self.point = Literal('.')

        self.plusorminus = Literal('+') | Literal('-')
        self.number = Word(nums)
        self.integer = Combine(Optional(self.plusorminus) + self.number)
        self.fnumber = Combine(
            self.integer +
            Optional(self.point + Optional(self.number)) +
            Optional(self.e + self.integer))

        self.tab = Literal('    ')

        self.ident = Word(alphas+'_', alphanums+'_')
        self.conseq_idents_numbs = OneOrMore(self.ident | self.fnumber)
        self.attrib = self.ident + OneOrMore('.'+self.ident)

        self.statement = (
            ZeroOrMore(
                (self.directive |
                 self.tab |
                 self.conseq_idents_numbs |
                 self.separator |
                 self.string_or_doc |
                 self.triple_quote)
            ) + Optional(self.comment).suppress()
        )

        self.attribs = (
            ZeroOrMore(
                (self.directive.suppress() |
                 self.tab.suppress() |
                 self.attrib |
                 self.ident.suppress() |
                 self.separator.suppress() |
                 self.fnumber.suppress() |
                 self.string_or_doc.suppress() |
                 self.triple_quote.suppress())
            ) + Optional(self.comment).suppress()
        )

        self.conseq_idents = (
            ZeroOrMore(
                (self.directive.suppress() |
                 self.tab.suppress() |
                 self.ident |
                 self.separator.suppress() |
                 self.fnumber.suppress() |
                 self.string.suppress())
            ) + Optional(self.comment).suppress()
        )

        self.conseq_idents_no_obfuscate = (
            ZeroOrMore(
                (self.directive.suppress() |
                 self.tab.suppress() |
                 self.ident |
                 self.separator.suppress() |
                 self.fnumber.suppress() |
                 self.string_or_doc.suppress() |
                 self.triple_quote.suppress())
            ) + Optional(self.comment).suppress()
        )

        self.attribs.setParseAction(self.add_attribs_reserveds)
        self.conseq_idents.setParseAction(self.add_conseq_idents)
        self.conseq_idents_no_obfuscate.setParseAction(
            self.add_conseq_idents_no_obfuscate)
#.........这里部分代码省略.........
开发者ID:rdevost,项目名称:pymixup,代码行数:103,代码来源:obfuscatebnf.py

示例14: Combine

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
#Variables
variable << ( Combine( Word(alphas) + ZeroOrMore( Word(alphas) | integer 
| Literal(UNDERSCORE) )))

#Array elements
arrayElem << ( (variable + Literal(S) + expression + Literal(PIECE)) )

#Identifiers
identifier = ( (arrayElem) ^ (variable) )

#Types
types = (Literal(LETTER) | Literal(NUMBER) | Literal(SENTENCE))

#Expressions
term << Group(functionCall ^ constant  ^ identifier ^ Group(lpar.suppress() 
+ expression + rpar.suppress())) 
notTerm = (ZeroOrMore(bitNot) + term)
unary = ZeroOrMore(plusMinus) + notTerm 
multiplication = Group(unary + (ZeroOrMore(multDivMod + unary )))
addition = Group(multiplication + (ZeroOrMore(plusMinus + multiplication)))
andExp = Group(addition + (ZeroOrMore(bitAnd + addition ))) 
xorExp = Group(andExp + (ZeroOrMore(bitXor + andExp ))) 
orExp = Group(xorExp + (ZeroOrMore(bitOr + xorExp ))) 
expression << Group(orExp)


#Boolean expressions
relationalExp << Group((expression + relationalOp + expression) | 
( ZeroOrMore(boolNot) + lpar.suppress() + relationalExp + rpar.suppress()))
boolAndExp = Group(relationalExp) + ZeroOrMore(boolAnd + Group(relationalExp)) 
开发者ID:irinaid,项目名称:MAlice,代码行数:32,代码来源:parsing.py

示例15: __repr__

# 需要导入模块: from pyparsing import Literal [as 别名]
# 或者: from pyparsing.Literal import suppress [as 别名]
        
    def __repr__(self):
        return "<variable " + str(self.name) + ">"


number = Regex(r"[\+\-]?(([0-9]+(\.[0-9]+)?)|(\.[0-9]+))")

comma = Literal(",")

name = Regex("[a-z][a-z0-9_]*")
var_name = Regex("[a-z][a-z0-9_]*")
var_name.setParseAction(lambda tokens: Variable(tokens))

element = Forward()
equation = Forward()
arguments = Group(equation) + ZeroOrMore(comma.suppress() + Group(equation))
function_or_element = (name + Literal("(").suppress() + Group(arguments) + 
                      Literal(")").suppress()).setParseAction(
                                 lambda tokens: Function(tokens)) | element


element << (var_name | number | (Literal("(").suppress() + Group(equation) + 
                             Literal(")").suppress()))
equation << (function_or_element + ZeroOrMore(infix + function_or_element))



# Now we have the actual evaluate function.

def evaluate(text, variables={}, functions={}):
    """
开发者ID:cynicalbastard,项目名称:jzbot,代码行数:33,代码来源:__init__.py


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