我们从Python开源项目中,提取了以下14个代码示例,用于说明如何使用pyparsing.nums()。
def __init__(self, calc = SimpleCalculator()): self.exprStack = [] def pushStack(s, l, t): self.exprStack.append(t[0]) integer = Word(nums).addParseAction(pushStack) addop = Literal('+') | Literal('-') mulop = Literal('*') | Literal('/') lpar = Literal('(') rpar = Literal(')') expr = Forward() atom = integer | lpar + expr + rpar term = atom + ZeroOrMore((mulop + atom).addParseAction(pushStack)) expr << term + ZeroOrMore((addop + term).addParseAction(pushStack)) self.expr = expr + StringEnd() self.opfun = { '+' : (lambda a, b: calc.add(a,b)), '-' : (lambda a, b: calc.sub(a,b)), '*' : (lambda a, b: calc.mul(a,b)), '/' : (lambda a, b: calc.div(a,b)) }
def __init__(self): real_word_dashes = Word(pyparsing.alphas + '-') punctuation = Word('.!?:,;-') punctuation_no_dash = Word('.!?:,;') punctuation_reference_letter = Word('.:,;-') printable = Word(pyparsing.printables, exact=1) letter = Word(pyparsing.alphas, exact=1) letter_reference = punctuation_reference_letter + letter nums = Word(pyparsing.nums) + Optional(letter) + \ ZeroOrMore(letter_reference) word_end = pyparsing.ZeroOrMore(Word(')') | Word('}') | Word(']')) + \ WordEnd() self.single_number = ( WordStart() + real_word_dashes + nums + word_end ) self.single_number_parens = ( printable + letter + Optional(punctuation_no_dash) + pyparsing.OneOrMore( Word('([{', exact=1) + pyparsing.OneOrMore(nums | Word('-')) + Word(')]}', exact=1) ) + word_end ) self.number_then_punctuation = ( printable + letter + nums + punctuation + pyparsing.ZeroOrMore(nums | punctuation) + word_end ) self.punctuation_then_number = ( printable + letter + punctuation_no_dash + nums + pyparsing.ZeroOrMore(punctuation | nums) + word_end )
def __parse_netem_delay_distro(self, line): parse_param_name = "delay" pattern = ( pp.SkipTo(parse_param_name, include=True) + pp.Word(pp.nums + ".msu") + pp.Word(pp.nums + ".msu")) try: parsed_list = pattern.parseString(line) self.__parsed_param[parse_param_name] = parsed_list[2] self.__parsed_param["delay-distro"] = parsed_list[3] except pp.ParseException: pass
def parse(self, ping_message): headline, packet_info_line, body_line_list = self._preprocess_parse( line_list=ping_message) packet_pattern = ( pp.Word(pp.nums) + pp.Literal("packets transmitted,") + pp.Word(pp.nums) + pp.Literal("received,") ) self._destination = self._parse_destination(headline) parse_list = packet_pattern.parseString(_to_unicode(packet_info_line)) self._packet_transmit = int(parse_list[0]) self._packet_receive = int(parse_list[2]) self._duplicates = self.__parse_duplicate(packet_info_line) try: rtt_line = body_line_list[1] except IndexError: return if typepy.is_null_string(rtt_line): return rtt_pattern = ( pp.Literal("rtt min/avg/max/mdev =") + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + pp.Word(pp.nums + "ms") ) parse_list = rtt_pattern.parseString(_to_unicode(rtt_line)) self._rtt_min = float(parse_list[1]) self._rtt_avg = float(parse_list[3]) self._rtt_max = float(parse_list[5]) self._rtt_mdev = float(parse_list[7])
def __parse_duplicate(line): packet_pattern = ( pp.SkipTo(pp.Word("+" + pp.nums) + pp.Literal("duplicates,")) + pp.Word("+" + pp.nums) + pp.Literal("duplicates,") ) try: duplicate_parse_list = packet_pattern.parseString( _to_unicode(line)) except pp.ParseException: return 0 return int(duplicate_parse_list[-2].strip("+"))
def parse(self, ping_message): headline, packet_info_line, body_line_list = self._preprocess_parse( line_list=ping_message) packet_pattern = ( pp.Literal("Packets: Sent = ") + pp.Word(pp.nums) + pp.Literal(", Received = ") + pp.Word(pp.nums) ) self._destination = self._parse_destination(headline) parse_list = packet_pattern.parseString(_to_unicode(packet_info_line)) self._packet_transmit = int(parse_list[1]) self._packet_receive = int(parse_list[3]) try: rtt_line = body_line_list[2].strip() except IndexError: return if typepy.is_null_string(rtt_line): return rtt_pattern = ( pp.Literal("Minimum = ") + pp.Word(pp.nums) + pp.Literal("ms, Maximum = ") + pp.Word(pp.nums) + pp.Literal("ms, Average = ") + pp.Word(pp.nums) ) parse_list = rtt_pattern.parseString(_to_unicode(rtt_line)) self._rtt_min = float(parse_list[1]) self._rtt_avg = float(parse_list[5]) self._rtt_max = float(parse_list[3])
def parse(self, ping_message): headline, packet_info_line, body_line_list = self._preprocess_parse( line_list=ping_message) packet_pattern = ( pp.Word(pp.nums) + pp.Literal("packets transmitted,") + pp.Word(pp.nums) + pp.Literal("packets received,") ) self._destination = self._parse_destination(headline) parse_list = packet_pattern.parseString(_to_unicode(packet_info_line)) self._packet_transmit = int(parse_list[0]) self._packet_receive = int(parse_list[2]) try: rtt_line = body_line_list[1] except IndexError: return if typepy.is_null_string(rtt_line): return rtt_pattern = ( pp.Literal("round-trip min/avg/max/stddev =") + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + pp.Word(pp.nums + "ms") ) parse_list = rtt_pattern.parseString(_to_unicode(rtt_line)) self._rtt_min = float(parse_list[1]) self._rtt_avg = float(parse_list[3]) self._rtt_max = float(parse_list[5]) self._rtt_mdev = float(parse_list[7])
def parse(self, ping_message): headline, packet_info_line, body_line_list = self._preprocess_parse( line_list=ping_message) packet_pattern = ( pp.Word(pp.nums) + pp.Literal("packets transmitted,") + pp.Word(pp.nums) + pp.Literal("packets received,") ) self._destination = self._parse_destination(headline) parse_list = packet_pattern.parseString(_to_unicode(packet_info_line)) self._packet_transmit = int(parse_list[0]) self._packet_receive = int(parse_list[2]) self._duplicates = self.__parse_duplicate(packet_info_line) try: rtt_line = body_line_list[1] except IndexError: return if typepy.is_null_string(rtt_line): return rtt_pattern = ( pp.Literal("round-trip min/avg/max =") + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + "/" + pp.Word(pp.nums + ".") + pp.Word(pp.nums + "ms") ) parse_list = rtt_pattern.parseString(_to_unicode(rtt_line)) self._rtt_min = float(parse_list[1]) self._rtt_avg = float(parse_list[3]) self._rtt_max = float(parse_list[5])
def entry(): name = Word(alphas, alphas+'_') value = Word(nums, nums+".").setResultsName('nominal_value') uncert = Word(nums).setResultsName('std_dev') value_uncert = value + Suppress("(") + uncert + Suppress(")") return Dict( Group(name + Suppress("=") + value_uncert ) )
def parser(self): # Define punctuation as suppressed literals. lparen, rparen, lbrack, rbrack, lbrace, rbrace, colon = \ map(pp.Suppress, "()[]{}:") integer = pp.Combine(pp.Optional(pp.oneOf("+ -")) + pp.Word(pp.nums)) \ .setName("integer") \ .setParseAction(lambda toks: int(toks[0])) real = pp.Combine(pp.Optional(pp.oneOf("+ -")) + pp.Word(pp.nums) + "." + pp.Optional(pp.Word(pp.nums)) + pp.Optional(pp.oneOf("e E") + pp.Optional(pp.oneOf("+ -")) + pp.Word(pp.nums))) \ .setName("real") \ .setParseAction(lambda toks: float(toks[0])) _datetime_arg = (integer | real) datetime_args = pp.Group(pp.delimitedList(_datetime_arg)) _datetime = pp.Suppress(pp.Literal('datetime') + pp.Literal("(")) + datetime_args + pp.Suppress(")") _datetime.setParseAction(lambda x: self._make_datetime(x[0])) tuple_str = pp.Forward() list_str = pp.Forward() dict_str = pp.Forward() list_item = real | integer | _datetime | pp.quotedString.setParseAction(pp.removeQuotes) | \ pp.Group(list_str) | tuple_str | dict_str tuple_str << (pp.Suppress("(") + pp.Optional(pp.delimitedList(list_item)) + pp.Optional(pp.Suppress(",")) + pp.Suppress(")")) tuple_str.setParseAction(lambda toks : tuple(toks.asList())) list_str << (lbrack + pp.Optional(pp.delimitedList(list_item) + pp.Optional(pp.Suppress(","))) + rbrack) dict_entry = pp.Group(list_item + colon + list_item) dict_str << (lbrace + pp.Optional(pp.delimitedList(dict_entry) + pp.Optional(pp.Suppress(","))) + rbrace) dict_str.setParseAction(lambda toks: dict(toks.asList())) return list_item
def parseTerms(): """ 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 ]* """ global terms if not terms: 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( "^" ) pi = CaselessLiteral( "PI" ) expr = Forward() atom = (Optional("-") + ( pi | e | fnumber | ident + lpar + expr + rpar ).setParseAction( pushFirst ) | ( lpar + expr.suppress() + rpar )).setParseAction(pushUMinus) # by defining exponentiation as "atom [ ^ factor ]..." instead of "atom [ ^ atom ]...", we get right-to-left exponents, instead of left-to-righ # that is, 2^3^2 = 2^(3^2), not (2^3)^2. factor = Forward() factor << atom + ZeroOrMore( ( expop + factor ).setParseAction( pushFirst ) ) term = factor + ZeroOrMore( ( multop + factor ).setParseAction( pushFirst ) ) expr << term + ZeroOrMore( ( addop + term ).setParseAction( pushFirst ) ) terms = expr return terms
def parse(self, device, text): self._clear() if typepy.is_null_string(text): return [] text = text.strip() entry_list = [] for line in text.splitlines(): if typepy.is_null_string(line): continue line = self._to_unicode(line.lstrip()) if re.search("qdisc netem|qdisc tbf", line) is None: continue self._clear() if re.search("qdisc netem", line) is not None: self.__parse_netem_param(line, "parent", pp.hexnums + ":") self.__parsed_param[Tc.Param.DEVICE] = device self.__parse_netem_param(line, "netem", pp.hexnums + ":", "handle") self.__parse_netem_param(line, "delay", pp.nums + ".msu") self.__parse_netem_delay_distro(line) self.__parse_netem_param(line, "loss", pp.nums + ".") self.__parse_netem_param(line, "duplicate", pp.nums + ".") self.__parse_netem_param(line, "corrupt", pp.nums + ".") self.__parse_netem_param(line, "reorder", pp.nums + ".") self.__parse_bandwidth_rate(line) logger.debug("parse a qdisc entry: {}".format(self.__parsed_param)) entry_list.append(self.__parsed_param) if entry_list: self.__con.create_table_from_data_matrix( table_name=self._tc_subcommand, attr_name_list=[ Tc.Param.DEVICE, "parent", "handle", "delay", "delay-distro", "loss", "duplicate", "corrupt", "reorder", "rate", ], data_matrix=entry_list) logger.debug("tc {:s} parse result: {}".format( self._tc_subcommand, json.dumps(entry_list, indent=4))) return entry_list
def _create_primitives(): global binary, ident, rvalue, number, quoted_string, semi, time_interval, slot_id, comp, config_type, stream, comment, stream_trigger, selector if ident is not None: return semi = Literal(u';').suppress() ident = Word(alphas+u"_", alphas + nums + u"_") number = Regex(u'((0x[a-fA-F0-9]+)|[+-]?[0-9]+)').setParseAction(lambda s, l, t: [int(t[0], 0)]) binary = Regex(u'hex:([a-fA-F0-9][a-fA-F0-9])+').setParseAction(lambda s, l, t: [unhexlify(t[0][4:])]) quoted_string = dblQuotedString comment = Literal('#') + restOfLine rvalue = number | quoted_string # Convert all time intervals into an integer number of seconds time_unit_multipliers = { u'second': 1, u'seconds': 1, u'minute': 60, u'minutes': 60, u'hour': 60*60, u'hours': 60*60, u'day': 60*60*24, u'days': 60*60*24, u'month': 60*60*24*30, u'months': 60*60*24*30, u'year': 60*60*24*365, u'years': 60*60*24*365, } config_type = oneOf('uint8_t uint16_t uint32_t int8_t int16_t int32_t uint8_t[] uint16_t[] uint32_t[] int8_t[] int16_t[] int32_t[] string binary') comp = oneOf('> < >= <= == ~=') time_unit = oneOf(u"second seconds minute minutes hour hours day days week weeks month months year years") time_interval = (number + time_unit).setParseAction(lambda s, l, t: [t[0]*time_unit_multipliers[t[1]]]) slot_id = Literal(u"controller") | (Literal(u'slot') + number) slot_id.setParseAction(lambda s,l,t: [SlotIdentifier.FromString(u' '.join([str(x) for x in t]))]) stream_modifier = Literal("system") | Literal("user") | Literal("combined") stream = Optional(Literal("system")) + oneOf("buffered unbuffered input output counter constant") + number + Optional(Literal("node")) stream.setParseAction(lambda s,l,t: [DataStream.FromString(u' '.join([str(x) for x in t]))]) all_selector = Optional(Literal("all")) + Optional(stream_modifier) + oneOf("buffered unbuffered inputs outputs counters constants") + Optional(Literal("nodes")) all_selector.setParseAction(lambda s,l,t: [DataStreamSelector.FromString(u' '.join([str(x) for x in t]))]) one_selector = Optional(Literal("system")) + oneOf("buffered unbuffered input output counter constant") + number + Optional(Literal("node")) one_selector.setParseAction(lambda s,l,t: [DataStreamSelector.FromString(u' '.join([str(x) for x in t]))]) selector = one_selector | all_selector trigger_comp = oneOf('> < >= <= ==') stream_trigger = Group((Literal(u'count') | Literal(u'value')) + Literal(u'(').suppress() - stream - Literal(u')').suppress() - trigger_comp - number).setResultsName('stream_trigger')