Python pyparsing.Suppress() Examples

The following are 27 code examples of pyparsing.Suppress(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyparsing , or try the search function .
Example #1
Source File: storm_control.py    From ccat with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #2
Source File: parser.py    From pdblp with MIT License 6 votes vote down vote up
def _parse(mystr):

    LBRACE, RBRACE, EQUAL = map(pp.Suppress, "{}=")
    field = pp.Word(pp.printables + ' ', excludeChars='[]=')
    field.addParseAction(pp.tokenMap(str.rstrip))
    string = pp.dblQuotedString().setParseAction(pp.removeQuotes)
    number = pp.pyparsing_common.number()
    date_expr = pp.Regex(r'\d\d\d\d-\d\d-\d\d')
    time_expr = pp.Regex(r'\d\d:\d\d:\d\d\.\d\d\d')
    nan = pp.Keyword('nan')
    scalar_value = (string | date_expr | time_expr | number | nan)

    list_marker = pp.Suppress("[]")
    value_list = pp.Forward()
    jobject = pp.Forward()

    memberDef1 = pp.Group(field + EQUAL + scalar_value)
    memberDef2 = pp.Group(field + EQUAL + jobject)
    memberDef3 = pp.Group(field + list_marker + EQUAL + LBRACE + value_list +
                          RBRACE)
    memberDef = memberDef1 | memberDef2 | memberDef3

    value_list <<= (pp.delimitedList(scalar_value, ",") |
                    pp.ZeroOrMore(pp.Group(pp.Dict(memberDef2))))
    value_list.setParseAction(lambda t: [pp.ParseResults(t[:])])

    members = pp.OneOrMore(memberDef)
    jobject <<= pp.Dict(LBRACE + pp.ZeroOrMore(memberDef) + RBRACE)
    # force empty jobject to be a dict
    jobject.setParseAction(lambda t: t or {})

    parser = members
    parser = pp.OneOrMore(pp.Group(pp.Dict(memberDef)))

    return parser.parseString(mystr) 
Example #3
Source File: sql_graphviz.py    From auptimizer with GNU General Public License v3.0 6 votes vote down vote up
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) 
Example #4
Source File: interpreter.py    From design-patterns with MIT License 6 votes vote down vote up
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 
Example #5
Source File: username.py    From ccat with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #6
Source File: stp_global.py    From ccat with GNU General Public License v3.0 6 votes vote down vote up
def _globalParse___stp_attributes(stp, dct):
    parse_portfast = Suppress('portfast ') + restOfLine
    parse_bpdu = Suppress('portfast bpduguard ') + restOfLine
    parse_loop = Suppress('loopguard ') + restOfLine
    try:
        return util.int_dict_parse(parse_bpdu, stp, 'bpduguard', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_loop, stp, 'loopguard', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_portfast, stp, 'portfast', dct)
    except ParseException:
        pass
    return 0 
Example #7
Source File: httpServerLogParser.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
def getLogLineBNF():
    global logLineBNF
    
    if logLineBNF is None:
        integer = Word( nums )
        ipAddress = delimitedList( integer, ".", combine=True )
        
        timeZoneOffset = Word("+-",nums)
        month = Word(string.uppercase, string.lowercase, exact=3)
        serverDateTime = Group( Suppress("[") + 
                                Combine( integer + "/" + month + "/" + integer +
                                        ":" + integer + ":" + integer + ":" + integer ) +
                                timeZoneOffset + 
                                Suppress("]") )
                         
        logLineBNF = ( ipAddress.setResultsName("ipAddr") + 
                       Suppress("-") +
                       ("-" | Word( alphas+nums+"@._" )).setResultsName("auth") +
                       serverDateTime.setResultsName("timestamp") + 
                       dblQuotedString.setResultsName("cmd").setParseAction(getCmdFields) +
                       (integer | "-").setResultsName("statusCode") + 
                       (integer | "-").setResultsName("numBytesSent")  + 
                       dblQuotedString.setResultsName("referrer").setParseAction(removeQuotes) +
                       dblQuotedString.setResultsName("clientSfw").setParseAction(removeQuotes) )
    return logLineBNF 
Example #8
Source File: parsing.py    From online-ratings with MIT License 5 votes vote down vote up
def _quoted(expr):
    return Combine(Suppress(Literal("'")) + expr + Suppress(Literal("'"))) 
Example #9
Source File: case_parser.py    From psst with MIT License 5 votes vote down vote up
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()] 
Example #10
Source File: ast.py    From gcl with MIT License 5 votes vote down vote up
def sym(sym):
  return p.Suppress(sym) 
Example #11
Source File: case_parser.py    From psst with MIT License 5 votes vote down vote up
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 
Example #12
Source File: modulefilter.py    From wfuzz with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self):
        if PYPARSING:
            category = Word(alphas + "_-*", alphanums + "_-*")
            operator = oneOf("and or ,")
            neg_operator = "not"
            elementRef = category
            definition = elementRef + ZeroOrMore(operator + elementRef)
            nestedformula = Group(Suppress(Optional(Literal("("))) + definition + Suppress(Optional(Literal(")"))))
            neg_nestedformula = Optional(neg_operator) + nestedformula
            self.finalformula = neg_nestedformula + ZeroOrMore(operator + neg_nestedformula)

            elementRef.setParseAction(self.__compute_element)
            neg_nestedformula.setParseAction(self.__compute_neg_formula)
            nestedformula.setParseAction(self.__compute_formula)
            self.finalformula.setParseAction(self.__myreduce) 
Example #13
Source File: safe_eval.py    From qkeras with Apache License 2.0 5 votes vote down vote up
def GetParams(s):
  """Extracts args and kwargs from string."""
  # modified from https://stackoverflow.com/questions/38799223/parse-string-to-identify-kwargs-and-args  # pylint: disable=line-too-long

  _lparen = Suppress("(")  # pylint: disable=invalid-name
  _rparen = Suppress(")")  # pylint: disable=invalid-name
  _eq = Suppress("=")  # pylint: disable=invalid-name

  data = (_lparen + Optional(
      delimitedList(
          Group(Regex(r"[^=,)\s]+") + Optional(_eq + Regex(u"[^,)]*")))
          )
      ) + _rparen)

  items = data.parseString(s).asList()

  # need to make sure that kwargs only happen after args are processed
  args = [Num(i[0]) for i in items if len(i) == 1]
  kwargs = {i[0]: Num(i[1]) for i in items if len(i) == 2}

  # check for syntax error
  for i in range(1, len(items)):
    if (len(items[i]) == 1) and (len(items[i-1]) == 2):
      raise SyntaxError

  return args, kwargs 
Example #14
Source File: fragment.py    From pybel with MIT License 5 votes vote down vote up
def get_fragment_language() -> ParserElement:
    """Build a protein fragment parser."""
    _fragment_value_inner = fragment_range | missing_fragment(FRAGMENT_MISSING)
    _fragment_value = _fragment_value_inner | And([Suppress('"'), _fragment_value_inner, Suppress('"')])
    parser_element = fragment_tag + nest(_fragment_value + Optional(WCW + quote(FRAGMENT_DESCRIPTION)))
    return parser_element 
Example #15
Source File: core.py    From fusesoc with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse(self, flags):
        _flags = []
        for k, v in flags.items():
            if v == True:
                _flags.append(k)
            elif v in [False, None]:
                pass
            else:
                _flags.append(k + "_" + v)

        def cb_conditional(s, l, t):
            if (t.cond in _flags) != (t.negate == "!"):
                return t.expr
            else:
                return []

        word = Word(alphanums + ":<>.[]_-,=~/^~")
        conditional = Forward()
        conditional << (
            Optional("!")("negate")
            + word("cond")
            + Suppress("?")
            + Suppress("(")
            + OneOrMore(conditional ^ word)("expr")
            + Suppress(")")
        ).setParseAction(cb_conditional)
        string = word
        string_list = OneOrMore(conditional ^ string)
        s = " ".join(string_list.parseString(self.__str__()))
        logger.debug(
            "Parsing '{}' with flags {} => {}".format(self.__str__(), str(_flags), s)
        )
        return s 
Example #16
Source File: vtp.py    From ccat with GNU General Public License v3.0 5 votes vote down vote up
def _globalParse___vtp_attributes(vtp, dct):
    parse_domain = Suppress('domain ') + restOfLine
    parse_mode = Suppress('mode ') + restOfLine
    try:
        return util.int_dict_parse(parse_domain, vtp, 'domain', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_mode, vtp, 'mode', dct)
    except ParseException:
        pass
    return 0 
Example #17
Source File: ip_iface.py    From ccat with GNU General Public License v3.0 5 votes vote down vote up
def __ifaceAttributes___ip_parse(value, dct):
    parse_mode = Word(alphas)
    parse_rate = Suppress('limit rate ') + restOfLine
    try:
        return util.int_dict_parse(parse_rate, value, 'limit', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_mode, value, 'mode', dct)
    except ParseException:
        pass 
Example #18
Source File: stringparser.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        # create parsing grammer
        sQStringLiteral = pyparsing.QuotedString("'")
        sQStringLiteral.setParseAction(
            lambda s, loc, toks: StringLiteral(s, loc, toks, False))

        dQStringLiteral = pyparsing.QuotedString('"', '\\')
        dQStringLiteral.setParseAction(
            lambda s, loc, toks: StringLiteral(s, loc, toks, True))

        stringLiteral = sQStringLiteral | dQStringLiteral

        functionCall = pyparsing.Forward()
        functionArg = stringLiteral | functionCall
        functionCall << pyparsing.Word(pyparsing.alphas, pyparsing.alphanums+'-') + \
            pyparsing.Suppress('(') + \
            pyparsing.Optional(functionArg +
                pyparsing.ZeroOrMore(pyparsing.Suppress(',') + functionArg)) + \
            pyparsing.Suppress(')')
        functionCall.setParseAction(
            lambda s, loc, toks: FunctionCall(s, loc, toks))

        predExpr = pyparsing.infixNotation(
            stringLiteral ^ functionCall ,
            [
                ('!',  1, pyparsing.opAssoc.RIGHT, lambda s, loc, toks: NotOperator(s, loc, toks)),
                ('<',  2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryStrOperator)),
                ('<=', 2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryStrOperator)),
                ('>',  2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryStrOperator)),
                ('>=', 2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryStrOperator)),
                ('==', 2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryStrOperator)),
                ('!=', 2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryStrOperator)),
                ('&&', 2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryBoolOperator)),
                ('||', 2, pyparsing.opAssoc.LEFT,  infixBinaryOp(BinaryBoolOperator))
            ])

        self.__ifgrammer = predExpr 
Example #19
Source File: port_security.py    From ccat with GNU General Public License v3.0 5 votes vote down vote up
def __ifaceAttributes___port_sec_parse(port, dct):
    parse_aging_time = Suppress('aging time ') + restOfLine
    parse_aging_type = Suppress('aging type ') + restOfLine
    parse_violat = Suppress('violation ') + restOfLine
    parse_max = Suppress('maximum ') + restOfLine
    parse_mac = Suppress('mac-address ') + Optional('sticky') + restOfLine
    try:
        return util.int_dict_parse(parse_aging_time, port, 'aging time', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_aging_type, port, 'aging type', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_violat, port, 'violation', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_mac, port, 'mac-address', dct)
    except ParseException:
        pass
    try:
        return util.int_dict_parse(parse_max, port, 'maximum', dct)
    except ParseException:
        pass 
Example #20
Source File: util.py    From ccat with GNU General Public License v3.0 5 votes vote down vote up
def get_attributes(config):
    options_list = []
    option = White(exact=1) + Suppress(Optional(White())) + restOfLine
    next_line = config.readline()
    try:
        option_parse = option.parseString(next_line)
        while option_parse[0] == ' ':
            options_list.append(option_parse[-1])
            next_line = config.readline()
            option_parse = option.parseString(next_line)
    except:
        pass
    return options_list, next_line 
Example #21
Source File: parse_concept.py    From pybel with MIT License 4 votes vote down vote up
def __init__(
        self,
        namespace_to_term_to_encoding: Optional[NamespaceTermEncodingMapping] = None,
        namespace_to_pattern: Optional[Mapping[str, Pattern]] = None,
        default_namespace: Optional[Set[str]] = None,
        allow_naked_names: bool = False,
        skip_validation: bool = False,
    ) -> None:
        """Initialize the concept parser.

        :param namespace_to_term_to_encoding: A dictionary of {namespace: {(identifier, name): encoding}}
        :param namespace_to_pattern: A dictionary of {namespace: regular expression string} to compile
        :param default_namespace: A set of strings that can be used without a namespace
        :param allow_naked_names: If true, turn off naked namespace failures
        """
        self.identifier_fqualified = (
            word(NAMESPACE)
            + Suppress(':')
            + (word | quote)(IDENTIFIER)
            + Suppress('!')
            + (word | quote)(NAME)
        )
        self.identifier_qualified = word(NAMESPACE) + Suppress(':') + (word | quote)(NAME)

        if namespace_to_term_to_encoding is not None:
            self.namespace_to_name_to_encoding = defaultdict(dict)
            self.namespace_to_identifier_to_encoding = defaultdict(dict)
            for namespace, term_mapping in namespace_to_term_to_encoding.items():
                for (identifier, name), encoding in term_mapping.items():
                    self.namespace_to_name_to_encoding[namespace][name] = encoding
                    self.namespace_to_identifier_to_encoding[namespace][identifier] = encoding

            self.namespace_to_name_to_encoding = dict(self.namespace_to_name_to_encoding)
            self.namespace_to_identifier_to_encoding = dict(self.namespace_to_identifier_to_encoding)
        else:
            self.namespace_to_name_to_encoding = {}
            self.namespace_to_identifier_to_encoding = {}

        if not skip_validation:
            self.identifier_fqualified.setParseAction(self.handle_identifier_fqualified)
            self.identifier_qualified.setParseAction(self.handle_identifier_qualified)

        self.namespace_to_pattern = namespace_to_pattern or {}
        self.default_namespace = set(default_namespace) if default_namespace is not None else None
        self.allow_naked_names = allow_naked_names

        self.identifier_bare = (word | quote)(NAME)
        self.identifier_bare.setParseAction(
            self.handle_namespace_default if self.default_namespace else
            self.handle_namespace_lenient if self.allow_naked_names else
            self.handle_namespace_invalid,
        )

        super().__init__(
            self.identifier_fqualified | self.identifier_qualified | self.identifier_bare,
        ) 
Example #22
Source File: jsLiteralParse.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def jsParse(inStr):
	# This disaster is a context-free grammar parser for parsing javascript object literals.
	# It needs to be able to handle a lot of the definitional messes you find in in-the-wild
	# javascript object literals.
	# Unfortunately, Javascript is /way/ more tolerant then JSON when it comes to object literals
	# so we can't just parse objects using python's `json` library.

	TRUE = pp.Keyword("true").setParseAction( pp.replaceWith(True) )
	FALSE = pp.Keyword("false").setParseAction( pp.replaceWith(False) )
	NULL = pp.Keyword("null").setParseAction( pp.replaceWith(None) )

	jsonString = pp.quotedString.setParseAction( pp.removeQuotes )
	jsonNumber = pp.Combine( pp.Optional('-') + ( '0' | pp.Word('123456789',pp.nums) ) +
											pp.Optional( '.' + pp.Word(pp.nums) ) +
											pp.Optional( pp.Word('eE',exact=1) + pp.Word(pp.nums+'+-',pp.nums) ) )

	jsonObject   = pp.Forward()
	jsonValue    = pp.Forward()
	jsonDict     = pp.Forward()
	jsonArray    = pp.Forward()
	jsonElements = pp.Forward()

	rawText      = pp.Regex('[a-zA-Z_$][0-9a-zA-Z_$]*')

	commaToNull = pp.Word(',,', exact=1).setParseAction(pp.replaceWith(None))
	jsonElements << pp.ZeroOrMore(commaToNull) + pp.Optional(jsonObject) + pp.ZeroOrMore((pp.Suppress(',') + jsonObject) | commaToNull)

	jsonValue << ( jsonString | jsonNumber | TRUE | FALSE | NULL )


	dictMembers = pp.delimitedList( pp.Group( (rawText | jsonString) + pp.Suppress(':') + (jsonValue | jsonDict | jsonArray)))
	jsonDict << ( pp.Dict( pp.Suppress('{') + pp.Optional(dictMembers) + pp.ZeroOrMore(pp.Suppress(',')) + pp.Suppress('}') ) )
	jsonArray << ( pp.Group(pp.Suppress('[') + pp.Optional(jsonElements) + pp.Suppress(']') ) )
	jsonObject << (jsonValue | jsonDict | jsonArray)

	jsonComment = pp.cppStyleComment
	jsonObject.ignore( jsonComment )

	def convertDict(s, l, toks):

		return dict(toks.asList())

	def convertNumbers(s,l,toks):
		n = toks[0]
		try:
			return int(n)
		except ValueError:
			return float(n)

	jsonNumber.setParseAction(convertNumbers)
	jsonDict.setParseAction(convertDict)

	# jsonObject.setDebug()
	jsonObject.parseString('"inStr"').pop()
	return jsonObject.parseString(inStr).pop()


# Stolen from http://stackoverflow.com/a/12017573/268006 
Example #23
Source File: interpreter.py    From Mastering-Python-Design-Patterns-Second-Edition with MIT License 4 votes vote down vote up
def main():  
    word = Word(alphanums)  
    command = Group(OneOrMore(word))  
    token = Suppress("->")  
    device = Group(OneOrMore(word))  
    argument = Group(OneOrMore(word))  
    event = command + token + device + Optional(token + argument)  
 
    gate = Gate()  
    garage = Garage()  
    airco = Aircondition()  
    heating = Heating()  
    boiler = Boiler()  
    fridge = Fridge()  

    tests = ('open -> gate',  
             'close -> garage',  
             'turn on -> air condition',  
             'turn off -> heating',  
             'increase -> boiler temperature -> 5 degrees',  
             'decrease -> fridge temperature -> 2 degrees')  

    open_actions = {'gate':gate.open, 
                    'garage':garage.open, 
                    'air condition':airco.turn_on,  
                    'heating':heating.turn_on, 
                    'boiler temperature':boiler.increase_temperature,  
                    'fridge temperature':fridge.increase_temperature}  
    close_actions = {'gate':gate.close, 
                     'garage':garage.close, 
                     'air condition':airco.turn_off,  
                     'heating':heating.turn_off, 
                     'boiler temperature':boiler.decrease_temperature,  
                     'fridge temperature':fridge.decrease_temperature}  

    for t in tests:  
        if len(event.parseString(t)) == 2: # no argument  
            cmd, dev = event.parseString(t)  
            cmd_str, dev_str = ' '.join(cmd), ' '.join(dev)  
            if 'open' in cmd_str or 'turn on' in cmd_str:  
                open_actions[dev_str]()  
            elif 'close' in cmd_str or 'turn off' in cmd_str:  
                close_actions[dev_str]()  
        elif len(event.parseString(t)) == 3: # argument  
            cmd, dev, arg = event.parseString(t)  
            cmd_str = ' '.join(cmd)
            dev_str = ' '.join(dev)
            arg_str = ' '.join(cmd)
            num_arg = 0  
            try:  
                # extract the numeric part
                num_arg = int(arg_str.split()[0])  
            except ValueError as err:  
                print(f"expected number but got: '{arg_str[0]}'")  
            if 'increase' in cmd_str and num_arg > 0:  
                open_actions[dev_str](num_arg)  
            elif 'decrease' in cmd_str and num_arg > 0:  
                close_actions[dev_str](num_arg) 
Example #24
Source File: searchparser.py    From patzilla with GNU Affero General Public License v3.0 4 votes vote down vote up
def parser(self):
        """
        This function returns a parser.
        The grammar should be like most full text search engines (Google, Tsearch, Lucene).

        Grammar:
        - a query consists of alphanumeric words, with an optional '*' wildcard
          at the end of a word
        - a sequence of words between quotes is a literal string
        - words can be used together by using operators ('and' or 'or')
        - words with operators can be grouped with parenthesis
        - a word or group of words can be preceded by a 'not' operator
        - the 'and' operator precedes an 'or' operator
        - if an operator is missing, use an 'and' operator
        """
        operatorOr = Forward()

        operatorWord = Word(wordchars).setResultsName('value')

        operatorQuotesContent = Forward()
        operatorQuotesContent << (
            (operatorWord + operatorQuotesContent) | operatorWord
            )

        operatorQuotes = Group(
            Suppress('"') + operatorQuotesContent + Suppress('"')
        ).setResultsName("quotes") | operatorWord

        prefix = (Word(alphanums).setResultsName('index') + Word('=').setResultsName('binop'))
        operatorParenthesis = Group(
            Optional(prefix) +
            (Suppress("(") + operatorOr + Suppress(")"))
        ).setResultsName("parenthesis") | Group(prefix + operatorQuotes).setResultsName('term') | operatorQuotes

        operatorNot = Forward()
        operatorNot << (Group(
            Suppress(Keyword("not", caseless=True)) + operatorNot
        ).setResultsName("not") | operatorParenthesis)

        operatorAnd = Forward()
        operatorAnd << (Group(
            operatorNot + Suppress(Keyword("and", caseless=True)) + operatorAnd
        ).setResultsName("and") | Group(
            operatorNot + OneOrMore(~oneOf("and or", caseless=True) + operatorAnd)
        ).setResultsName("and") | operatorNot)

        operatorProximity = Forward()
        operatorProximity << (Group(
            operatorParenthesis + Suppress(Literal("near,")) + Word(nums).setResultsName('distance') + operatorParenthesis
        ).setResultsName("near") | Group(
            operatorParenthesis + Suppress(Literal("span,")) + Word(nums).setResultsName('distance') + operatorParenthesis
        ).setResultsName("span") | operatorAnd)

        operatorOr << (Group(
            operatorProximity + Suppress(Keyword("or", caseless=True)) + operatorOr
        ).setResultsName("or") | operatorProximity)

        return operatorOr.parseString 
Example #25
Source File: interpreter.py    From Python_Master-the-Art-of-Design-Patterns with MIT License 4 votes vote down vote up
def main():
    word = Word(alphanums)
    command = Group(OneOrMore(word))
    token = Suppress("->")
    device = Group(OneOrMore(word))
    argument = Group(OneOrMore(word))
    event = command + token + device + Optional(token + argument)

    gate = Gate()
    garage = Garage()
    airco = Aircondition()
    heating = Heating()
    boiler = Boiler()
    fridge = Fridge()

    tests = ('open -> gate',
             'close -> garage',
             'turn on -> aircondition',
             'turn off -> heating',
             'increase -> boiler temperature -> 5 degrees',
             'decrease -> fridge temperature -> 2 degrees')

    open_actions = {'gate':gate.open, 'garage':garage.open, 'aircondition':airco.turn_on,
                  'heating':heating.turn_on, 'boiler temperature':boiler.increase_temperature,
                  'fridge temperature':fridge.increase_temperature}
    close_actions = {'gate':gate.close, 'garage':garage.close, 'aircondition':airco.turn_off,
                   'heating':heating.turn_off, 'boiler temperature':boiler.decrease_temperature,
                   'fridge temperature':fridge.decrease_temperature}

    for t in tests:
        if len(event.parseString(t)) == 2: # no argument
            cmd, dev = event.parseString(t)
            cmd_str, dev_str = ' '.join(cmd), ' '.join(dev)
            if 'open' in cmd_str or 'turn on' in cmd_str:
                open_actions[dev_str]()
            elif 'close' in cmd_str or 'turn off' in cmd_str:
                close_actions[dev_str]()
        elif len(event.parseString(t)) == 3: # argument
            cmd, dev, arg = event.parseString(t)
            cmd_str, dev_str, arg_str = ' '.join(cmd), ' '.join(dev), ' '.join(arg)
            num_arg = 0
            try:
                num_arg = int(arg_str.split()[0]) # extract the numeric part
            except ValueError as err:
                print("expected number but got: '{}'".format(arg_str[0]))
            if 'increase' in cmd_str and num_arg > 0:
                open_actions[dev_str](num_arg)
            elif 'decrease' in cmd_str and num_arg > 0:
                close_actions[dev_str](num_arg) 
Example #26
Source File: interpreter.py    From Python_Master-the-Art-of-Design-Patterns with MIT License 4 votes vote down vote up
def main():
    word = Word(alphanums)
    command = Group(OneOrMore(word))
    token = Suppress("->")
    device = Group(OneOrMore(word))
    argument = Group(OneOrMore(word))
    event = command + token + device + Optional(token + argument)

    gate = Gate()
    garage = Garage()
    airco = Aircondition()
    heating = Heating()
    boiler = Boiler()
    fridge = Fridge()

    tests = ('open -> gate',
             'close -> garage',
             'turn on -> aircondition',
             'turn off -> heating',
             'increase -> boiler temperature -> 20 degrees',
             'decrease -> fridge temperature -> 6 degree')

    open_actions = {'gate':gate.open, 'garage':garage.open, 'aircondition':airco.turn_on,
                  'heating':heating.turn_on, 'boiler temperature':boiler.increase_temperature,
                  'fridge temperature':fridge.increase_temperature}
    close_actions = {'gate':gate.close, 'garage':garage.close, 'aircondition':airco.turn_off,
                   'heating':heating.turn_off, 'boiler temperature':boiler.decrease_temperature,
                   'fridge temperature':fridge.decrease_temperature}

    for t in tests:
        if len(event.parseString(t)) == 2: # no argument
            cmd, dev = event.parseString(t)
            cmd_str, dev_str = ' '.join(cmd), ' '.join(dev)
            if 'open' in cmd_str or 'turn on' in cmd_str:
                open_actions[dev_str]()
            elif 'close' in cmd_str or 'turn off' in cmd_str:
                close_actions[dev_str]()
        elif len(event.parseString(t)) == 3: # argument
            cmd, dev, arg = event.parseString(t)
            cmd_str, dev_str, arg_str = ' '.join(cmd), ' '.join(dev), ' '.join(arg)
            num_arg = 0
            try:
                num_arg = int(arg_str.split()[0]) # extract the numeric part
            except ValueError as err:
                print("expected number but got: '{}'".format(arg_str[0]))
            if 'increase' in cmd_str and num_arg > 0:
                open_actions[dev_str](num_arg)
            elif 'decrease' in cmd_str and num_arg > 0:
                close_actions[dev_str](num_arg) 
Example #27
Source File: searchparser.py    From phpsploit with GNU General Public License v3.0 4 votes vote down vote up
def parser(self):
        """
        This function returns a parser.
        The grammar should be like most full text search engines (Google, Tsearch, Lucene).
        
        Grammar:
        - a query consists of alphanumeric words, with an optional '*' wildcard
          at the end of a word
        - a sequence of words between quotes is a literal string
        - words can be used together by using operators ('and' or 'or')
        - words with operators can be grouped with parenthesis
        - a word or group of words can be preceded by a 'not' operator
        - the 'and' operator precedes an 'or' operator
        - if an operator is missing, use an 'and' operator
        """
        operatorOr = Forward()
        
        operatorWord = Group(Combine(Word(alphanums) + Suppress('*'))).setResultsName('wordwildcard') | \
                            Group(Word(alphanums)).setResultsName('word')
        
        operatorQuotesContent = Forward()
        operatorQuotesContent << (
            (operatorWord + operatorQuotesContent) | operatorWord
        )
        
        operatorQuotes = Group(
            Suppress('"') + operatorQuotesContent + Suppress('"')
        ).setResultsName("quotes") | operatorWord
        
        operatorParenthesis = Group(
            (Suppress("(") + operatorOr + Suppress(")"))
        ).setResultsName("parenthesis") | operatorQuotes

        operatorNot = Forward()
        operatorNot << (Group(
            Suppress(Keyword("not", caseless=True)) + operatorNot
        ).setResultsName("not") | operatorParenthesis)

        operatorAnd = Forward()
        operatorAnd << (Group(
            operatorNot + Suppress(Keyword("and", caseless=True)) + operatorAnd
        ).setResultsName("and") | Group(
            operatorNot + OneOrMore(~oneOf("and or") + operatorAnd)
        ).setResultsName("and") | operatorNot)
        
        operatorOr << (Group(
            operatorAnd + Suppress(Keyword("or", caseless=True)) + operatorOr
        ).setResultsName("or") | operatorAnd)

        return operatorOr.parseString