本文整理汇总了Python中pyparsing.Suppress.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Suppress.setParseAction方法的具体用法?Python Suppress.setParseAction怎么用?Python Suppress.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Suppress
的用法示例。
在下文中一共展示了Suppress.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def parse(self, header):
comment = self._comment()
quoted = quotedString.copy().setParseAction(removeQuotes)
string = quoted | Word(printables, excludeChars='{},%')
enum_value = quotedString | Word(printables, excludeChars='{},%')
relation = (Suppress(CaselessLiteral("@relation")) +
Optional(restOfLine, default='default_name')('rel_name').setParseAction(lambda t: t.rel_name.strip()))
relation_part = ZeroOrMore(comment) + relation + ZeroOrMore(comment)
nominal = (Empty().copy().setParseAction(lambda t: self.ENUM) +
Suppress(Literal("{")) +
Group(delimitedList(enum_value, delim=self._separator))("next_arg").setParseAction(self.get_values) +
Suppress(Literal("}")))
date = CaselessLiteral("date") + Optional(CharsNotIn("{},\n"))("next_arg").setParseAction(self._adapt_date_format)
attributes_part = Forward()
relational = CaselessLiteral("relational") + attributes_part + Suppress(CaselessLiteral("@end")) + string
attr_type = (CaselessLiteral("numeric") | CaselessLiteral("string") | nominal | date | relational)("attr_type")
attribute = Suppress(CaselessLiteral("@attribute")) + (string.copy())("attr_name") + attr_type
attribute_line = comment | attribute
attributes_part << (Group(OneOrMore(attribute_line)))("children")
data_part = (CaselessLiteral("@data"))("data_start").setParseAction(lambda s, p, k: (lineno(p, s)))
arff_header = relation_part + attributes_part + data_part
attribute.setParseAction(self._create_attribute)
try:
result = arff_header.parseString(header, parseAll=True)
except ParseException as e:
raise HeaderError(FileType.ARFF, e.lineno, e.col, e.line, e)
self._relation_name = result.rel_name
self._find_relational(result.children)
self._linearize_attrs(result.children)
self._data_start = result.data_start
self._index = 0
示例2: parse
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def parse(date_string):
# Parser for individual dates
days_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday',
'Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun']
suffixes = Literal('nd') | Literal('rd') | Literal('st') | Literal('th')
day_of_month = Group(Word(nums) + Suppress(Optional(suffixes))).setResultsName('day')
single_date = Optional(DateParser._build_literal(days_of_week)).setResultsName('dow') + day_of_month + \
Optional(DateParser._build_literal(LONG_MONTHS + SHORT_MONTHS)).setResultsName('month') + \
Optional(Word(nums)).setResultsName('year')
single_date.setParseAction(SingleDate)
# Parser for date ranges
date_range_separators = DateParser._build_literal(['-', 'until', 'to'])
date_range = Suppress(Optional('From')) + single_date.setResultsName('start_date') + \
Suppress(date_range_separators) + single_date.setResultsName('end_date')
date_range.setParseAction(DateRange)
date_parser = (date_range | single_date) + stringEnd
result = date_parser.parseString(date_string)
return result
示例3: init_parser
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def init_parser(self):
INTEGER = Word(nums)
INTEGER.setParseAction(lambda x: int(x[0]))
header = INTEGER("species_count") + INTEGER("sequence_length") +\
Suppress(restOfLine)
header.setParseAction(self.set_header)
sequence_name = Word(
alphas + nums + "!#$%&\'*+-./;<=>[email protected][\\]^_`{|}~",
max=100)
# Take a copy and disallow line breaks in the bases
bases = self.BASES.copy()
bases.setWhitespaceChars(" \t")
seq_start = sequence_name("species") + bases(
"sequence") + Suppress(LineEnd())
seq_start.setParseAction(self.set_seq_start)
seq_start_block = OneOrMore(seq_start)
seq_start_block.setParseAction(self.set_start_block)
seq_continue = bases("sequence") + Suppress(LineEnd())
seq_continue.setParseAction(self.set_seq_continue)
seq_continue_block = Suppress(LineEnd()) + OneOrMore(seq_continue)
seq_continue_block.setParseAction(self.set_continue_block)
return header + seq_start_block + ZeroOrMore(seq_continue_block)
示例4: setup
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def setup(self):
# some expressions that will be reused
units = []
for unit in time_units:
units.append(Keyword(unit))
units = get_match_first(units)
units = units.setResultsName("unit")
units.setParseAction(lambda s, l, tok: time_units[tok[0]])
multiplier = Word(nums)
multiplier = multiplier.setResultsName("multiply")
multiplier.setParseAction(self.parseMulti)
adder = []
for add in add_modifiers:
adder.append(CL(add))
adder = get_match_first(adder)
adder = adder.setResultsName("add")
adder.setParseAction(self.parseAdd)
modifier = (multiplier | adder) # + FollowedBy(units)
# ago
#
# e.g 5 days ago
ago = Optional(modifier) + units + Suppress(Word("ago"))
ago.setParseAction(self.parseAgo)
# time range
#
# e.g in the lat 10 days
time_range = Suppress(Optional(
CL("in the"))) + \
Suppress(Word("last") |
Word("past")) + \
Optional(modifier) + \
units
time_range.setParseAction(self.parseRange)
# special keyword handling
#
# e.g yesterday
# only handles yesterday right now, maybe need to be modified to do
# more
special_expr = []
for expr in special:
special_expr.append(
Keyword(expr).setParseAction(
lambda s, l, tok: special[tok[0]]))
special_expr = get_match_first(special_expr)
special_expr = special_expr.setResultsName("unit")
special_expr.setParseAction(self.parseAgo)
parser = (special_expr | ago | time_range)
return parser
示例5: parser
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [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
示例6: __init__
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def __init__(self, datatype):
if datatype == "protein":
letters = "ARNDCQEGHILKMFPSTWYV"
elif datatype == "DNA":
letters = "ATCG"
else:
log.error("Unknown datatype '%s', please check" % datatype)
raise RaxmlError
FLOAT = Word(nums + '.-').setParseAction(lambda x: float(x[0]))
L = Word(letters, exact=1)
COLON = Suppress(":")
LNL_LABEL = Regex("Final GAMMA.+:") | Literal("Likelihood:")
TIME_LABEL = Regex("Overall Time.+:") | Regex("Overall Time.+tion ")
ALPHA_LABEL = Literal("alpha:")
TREE_SIZE_LABEL = Literal("Tree-Length:")
def labeled_float(label):
return Suppress(SkipTo(label)) + Suppress(label) + FLOAT
lnl = labeled_float(LNL_LABEL)
lnl.setParseAction(self.set_lnl)
seconds = labeled_float(TIME_LABEL)
seconds.setParseAction(self.set_seconds)
alpha = labeled_float(ALPHA_LABEL)
alpha.setParseAction(self.set_alpha)
tree_size = labeled_float(TREE_SIZE_LABEL)
tree_size.setParseAction(self.set_tree_size)
rate = Suppress("rate") + L + Suppress("<->") + L + COLON + FLOAT
rate.setParseAction(self.set_rate)
rates = OneOrMore(rate)
freq = Suppress("freq pi(") + L + Suppress("):") + FLOAT
freq.setParseAction(self.set_freq)
freqs = OneOrMore(freq)
# Just look for these things
self.root_parser = seconds + lnl + alpha + tree_size + rates + freqs
示例7: detect_token
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def detect_token(jade):
doctype = LineStart() + oneOf('!!! doctype') + Optional(oneOf('5 html xml' \
+ ' default transitional strict frameset 1.1 basic mobile', True))
doctype.setParseAction(parse_doctype)
element_id = Suppress('#') + Word(alphanums + '_' + '-')
element_class = Suppress('.') + Word(alphanums + '_' + '-')
selectors = (element_id.setResultsName('element_id') \
+ ZeroOrMore(element_class).setResultsName('element_class')) \
| (OneOrMore(element_class).setResultsName('element_class') \
+ Optional(element_id).setResultsName('element_id'))
selectors.setParseAction(parse_selectors)
element = selectors.setResultsName('selectors') \
| (Word(alphas).setResultsName('element_name') \
+ Optional(selectors).setResultsName('selectors'))
element.setParseAction(parse_element)
attribute = CharsNotIn('('+')')
attributes = nestedExpr(content=attribute)
tag = element.setResultsName('element') \
+ Optional(attributes).setResultsName('attributes')
tag.setParseAction(parse_tag)
# TODO: block-comment and conditional-comment
unbuffered_comment = Suppress(Suppress('//-') + restOfLine)
buffered_comment = Suppress('//') + restOfLine
buffered_comment.setParseAction(parse_buffered_comment)
# Order matters here, as buffered will pick up
# unbuffered comments if set first
comment = unbuffered_comment | buffered_comment
source = doctype | tag | comment
parsed = source.parseString(jade)
return ' '.join(parsed)
'''
示例8: __init__
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
class Compiler:
def __init__(self):
self._pythonVar = None
self.varNames = []
Preprocess.setSocialiteModule(getModuleVar())
def pythonVar(self):
if not self._pythonVar:
from pyparsing import (ParserElement, Word, alphas, alphanums,
Literal, Suppress, FollowedBy)
_ws = ' \t'
ParserElement.setDefaultWhitespaceChars(_ws)
ident = Word(alphas+"_", alphanums+"_")
lparen = Literal("(")
dot = Literal(".")
dollar = Literal("$")
self._pythonVar = Suppress(dollar) + ident + ~FollowedBy((dot+ident) | lparen)
self._pythonVar.setParseAction(self.onPythonVar)
return self._pythonVar
def compile(self, src):
gen=Preprocess.run(src)
return gen
def processPythonVars(self, query):
query = '('+query+')'
tmp = query
if tmp.find("$") >= 0: tmp = self.pythonVar().transformString(query)
if self.varNames:
query = ''.join([tmp, "%"+getPassVarsFunc()+"(", ','.join(self.varNames), ")"])
else: query = tmp
for i in xrange(len(self.varNames)):
self.varNames.pop()
return query
def onPythonVar(self, inputStr, loc, tokens):
varName = ''.join(tokens)
self.varNames.append(varName)
return "%s"
示例9: ListParser
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def ListParser():
"""
A parser for list columns, where each list is composed of pairs of values.
"""
value = Regex(r'[-+]?[0-9]+(?:\.[0-9]*)?(?:e[-+]?[0-9]+)?', IGNORECASE)
value.setParseAction(lambda toks: float(toks[0]))
item = Suppress('(') + value + Suppress(',') + value + Suppress(')')
item.setParseAction(tuple)
lst = Suppress('[') + delimitedList(item) + Suppress(']')
lst.setParseAction(list)
def parse(s):
try:
return lst.parseString(s).asList()
except ParseBaseException as e:
raise ValueError(e)
return parse
示例10: getEbnfParser
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def getEbnfParser(symbols):
""" Returns an EBNF parser for the command language. """
identifier = Word(alphas + '_', alphanums + '_')
string = quotedString.setParseAction(
lambda t: symbols.append((t[0][1:-1], TokenType.StrLit))
)
integer = Word(nums).setParseAction(
lambda t: symbols.append((int(t[0]), TokenType.NumLit))
)
var = Suppress("$") + identifier
var.setParseAction(
lambda t: symbols.append((t[0], TokenType.Var))
)
literal = var | string | integer
fnid = Suppress(Optional(".")) + identifier
fnid.setParseAction(
lambda t: symbols.append((t[0], TokenType.Call))
)
call = Forward()
callb = fnid + ZeroOrMore(call | literal)
call << ((Suppress("(") + callb + Suppress(")")) | callb)
fndef_head = Suppress("let") + identifier
fndef_head.setParseAction(
lambda t: symbols.append((t[0], TokenType.Def))
)
definition = fndef_head + ZeroOrMore(var) + Suppress("=") + call
cmd = OneOrMore((definition | call) + Word(";").setParseAction(
lambda t: symbols.append((t[0], TokenType.End))
))
msg = OneOrMore(cmd)
return msg
示例11: single
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
data = single | tuple_
# should not match a single (tr)
simple_data = Group(NotAny('(tr)') + data + ZeroOrMore(Optional(Suppress(',')) + data))
# the first element of a set data record cannot be 'dimen', or else
# these would match set_def_stmts
non_dimen_simple_data = ~Literal('dimen') + simple_data
matrix_row = Group(single + OneOrMore(PLUS | MINUS))
matrix_data = ":" + OneOrMore(single).setResultsName('columns') \
+ ":=" + OneOrMore(matrix_row).setResultsName('data')
matrix_data.setParseAction(MatrixData)
tr_matrix_data = Suppress("(tr)") + matrix_data
tr_matrix_data.setParseAction(mark_transposed)
set_slice_component = number | symbol | '*'
set_slice_record = LPAREN + NotAny('tr') + delimitedList(set_slice_component) + RPAREN
set_slice_record.setParseAction(SliceRecord)
_set_record = set_slice_record | matrix_data | tr_matrix_data | Suppress(":=")
set_record = simple_data | _set_record
non_dimen_set_record = non_dimen_simple_data | _set_record
set_def_stmt = "set" + symbol + Optional(subscript_domain) + \
Optional("dimen" + integer.setResultsName('dimen')) + END
set_def_stmt.setParseAction(SetDefStmt)
set_member = LBRACKET + delimitedList(data) + RBRACKET
示例12: __init__
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
def __init__(self, processor, baseiri, strict=False):
"""
See class docstring.
"""
# pylint: disable=R0914,R0915
self.reset(processor, baseiri, strict)
PrefixedName = PNAME_LN | PNAME_NS
Iri = IRIREF | PrefixedName
BNode = BLANK_NODE_LABEL | ANON
RDFLiteral = STRING + Optional(LANGTAG("langtag") | Group(Suppress("^^") + Iri)("datatype"))
Object = Forward()
Collection = Suppress("(") + ZeroOrMore(Object) + Suppress(")")
PredicateObjectList = Forward()
BlankNodePropertyList = Suppress("[") + PredicateObjectList + Suppress("]")
TtlLiteral = RDFLiteral | NUMERIC_LITERAL | BOOLEAN_LITERAL
Subject = Iri | BNode | Collection | VARIABLE # added for LD Patch
Predicate = Iri
Object << ( # pylint: disable=W0104
Iri | BNode | Collection | BlankNodePropertyList | TtlLiteral | VARIABLE
) # added for LD Patch
Verb = Predicate | Keyword("a")
ObjectList = Group(Object + ZeroOrMore(COMMA + Object))
PredicateObjectList << ( # pylint: disable=W0106
Verb + ObjectList + ZeroOrMore(SEMICOLON + Optional(Verb + ObjectList))
)
Triples = (Subject + PredicateObjectList) | (BlankNodePropertyList + Optional(PredicateObjectList))
Value = Iri | TtlLiteral | VARIABLE
InvPredicate = Suppress("^") + Predicate
Step = Suppress("/") + (Predicate | InvPredicate | INDEX)
Filter = Forward()
Constraint = Filter | UNICITY_CONSTRAINT
Path = Group(OneOrMore(Step | Constraint))
Filter << (
Suppress("[") # pylint: disable=W0106
+ Group(ZeroOrMore(Step | Constraint))("path") # = Path (*)
+ Optional(Suppress("=") + Object)("value")
+ Suppress("]")
)
# (*) we can not reuse the Path rule defined above,
# because we want to set a name for that component
Turtle = Triples + ZeroOrMore(PERIOD + Triples) + Optional(PERIOD)
Graph = Suppress("{") + Optional(Turtle) + Suppress("}")
Prefix = Literal("@prefix") + PNAME_NS + IRIREF + PERIOD
if not strict:
SparqlPrefix = CaselessKeyword("prefix") + PNAME_NS + IRIREF
Prefix = Prefix | SparqlPrefix
Bind = BIND_CMD + VARIABLE + Value + Optional(Path) + PERIOD
Add = ADD_CMD + Graph + PERIOD
AddNew = ADDNEW_CMD + Graph + PERIOD
Delete = DELETE_CMD + Graph + PERIOD
DeleteExisting = DELETEEXISTING_CMD + Graph + PERIOD
Cut = CUT_CMD + VARIABLE + PERIOD
UpdateList = UPDATELIST_CMD + Subject + Predicate + SLICE + Collection + PERIOD
Statement = Prefix | Bind | Add | AddNew | Delete | DeleteExisting | Cut | UpdateList
Patch = ZeroOrMore(Statement)
if not strict:
Patch.ignore("#" + restOfLine) # Comment
Patch.parseWithTabs()
self.grammar = Patch
IRIREF.setParseAction(self._parse_iri)
PrefixedName.setParseAction(self._parse_pname)
RDFLiteral.setParseAction(self._parse_turtleliteral)
Collection.setParseAction(self._parse_collection)
BlankNodePropertyList.setParseAction(self._parse_bnpl)
Verb.setParseAction(self._parse_verb)
ObjectList.setParseAction(self._parse_as_list)
Triples.setParseAction(self._parse_tss)
InvPredicate.setParseAction(self._parse_invpredicate)
Filter.setParseAction(self._parse_filter)
Path.setParseAction(self._parse_as_list)
Prefix.setParseAction(self._do_prefix)
Bind.setParseAction(self._do_bind)
Add.setParseAction(self._do_add)
AddNew.setParseAction(self._do_add_new)
Delete.setParseAction(self._do_delete)
DeleteExisting.setParseAction(self._do_delete_existing)
Cut.setParseAction(self._do_cut)
UpdateList.setParseAction(self._do_updatelist)
示例13: Literal
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
_word_function = Literal("extend") + Suppress("(") + _basic_expr + "," + _basic_expr + Suppress(")") | Literal(
"resize"
) + Suppress("(") + _basic_expr + "," + _basic_expr + Suppress(")")
_word_function.setParseAction(lambda s, l, t: WordFunction(t[0], t[1], t[2]))
_count = Literal("count") + Suppress("(") + delimitedList(_basic_expr) + Suppress(")")
_count.setParseAction(lambda s, l, t: Count(t[1]))
_next = Literal("next") + Suppress("(") + _basic_expr + Suppress(")")
_next.setParseAction(lambda s, l, t: Next(t[1]))
_case_case = _basic_expr + Suppress(":") + _basic_expr + Suppress(";")
_case_body = OneOrMore(_case_case)
_case_body.setParseAction(lambda s, l, t: OrderedDict(zip(t[::2], t[1::2])))
_case = Suppress("case") + _case_body + Suppress("esac")
_case.setParseAction(lambda s, l, t: Case(t[0]))
_base = complex_identifier ^ (
_conversion | _word_function | _count | _next | Suppress("(") + _basic_expr + Suppress(")") | _case | constant
)
_ap = Forward()
_array_subscript = Group(Suppress("[") + _basic_expr + Suppress("]"))
_word_bit_selection = Group(Suppress("[") + _basic_expr + Suppress(":") + _basic_expr + Suppress("]"))
_ap <<= Optional(_array_subscript + _ap | _word_bit_selection + _ap)
_array = _base + _ap
def _handle_array(tokens):
示例14: _build_asn1_grammar
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
#.........这里部分代码省略.........
boolean_type = BOOLEAN
real_type = REAL
null_type = NULL
object_identifier_type = OBJECT_IDENTIFIER
octetstring_type = OCTET_STRING + Optional(size_constraint)
unrestricted_characterstring_type = CHARACTER_STRING
restricted_characterstring_type = BMPString | GeneralString | \
GraphicString | IA5String | \
ISO646String | NumericString | \
PrintableString | TeletexString | \
T61String | UniversalString | \
UTF8String | VideotexString | VisibleString
characterstring_type = restricted_characterstring_type | unrestricted_characterstring_type
useful_type = GeneralizedTime | UTCTime | ObjectDescriptor
# todo: consider other builtins from 16.2
simple_type = (boolean_type | null_type | octetstring_type | characterstring_type | real_type | plain_integer_type | object_identifier_type | useful_type) + Optional(constraint)
constructed_type = choice_type | sequence_type | set_type
value_list_type = restricted_integer_type | enumerated_type
builtin_type = value_list_type | tagged_type | simple_type | constructed_type | sequenceof_type | setof_type | bitstring_type
type_ << (builtin_type | referenced_type)
# EXT: identifier should not be Optional here, but
# our other ASN.1 code generator supports unnamed members,
# and we use them.
named_type << (Optional(identifier) + type_)
type_assignment = typereference + '::=' + type_
value_assignment = valuereference + type_ + '::=' + value
assignment = type_assignment | value_assignment
assignment_list = ZeroOrMore(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
symbols_from_module_list = OneOrMore(symbols_from_module)
symbols_imported = Optional(symbols_from_module_list)
exports = Optional(Suppress(EXPORTS) + symbol_list + Suppress(';'))
imports = Optional(Suppress(IMPORTS) + symbols_imported + Suppress(';'))
module_body = (exports + imports + assignment_list)
module_defaults = Suppress(tag_default + extension_default) # we don't want these in the AST
module_identifier = module_reference + definitive_identifier
module_definition = module_identifier + DEFINITIONS + module_defaults + '::=' + BEGIN + module_body + END
module_definition.ignore(comment)
# Mark up the parse results with token tags
identifier.setParseAction(annotate('Identifier'))
named_number_value.setParseAction(annotate('Value'))
tag.setParseAction(annotate('Tag'))
class_.setParseAction(annotate('TagClass'))
class_number.setParseAction(annotate('TagClassNumber'))
type_.setParseAction(annotate('Type'))
simple_type.setParseAction(annotate('SimpleType'))
choice_type.setParseAction(annotate('ChoiceType'))
sequence_type.setParseAction(annotate('SequenceType'))
set_type.setParseAction(annotate('SetType'))
value_list_type.setParseAction(annotate('ValueListType'))
bitstring_type.setParseAction(annotate('BitStringType'))
referenced_type.setParseAction(annotate('ReferencedType'))
sequenceof_type.setParseAction(annotate('SequenceOfType'))
setof_type.setParseAction(annotate('SetOfType'))
named_number.setParseAction(annotate('NamedValue'))
constraint.setParseAction(annotate('Constraint'))
size_constraint.setParseAction(annotate('SizeConstraint'))
component_type.setParseAction(annotate('ComponentType'))
component_type_optional.setParseAction(annotate('ComponentTypeOptional'))
component_type_default.setParseAction(annotate('ComponentTypeDefault'))
component_type_components_of.setParseAction(annotate('ComponentTypeComponentsOf'))
tagged_type.setParseAction(annotate('TaggedType'))
named_type.setParseAction(annotate('NamedType'))
type_assignment.setParseAction(annotate('TypeAssignment'))
value_assignment.setParseAction(annotate('ValueAssignment'))
valuereference.setParseAction(annotate('ValueReference'))
module_reference.setParseAction(annotate('ModuleReference'))
module_body.setParseAction(annotate('ModuleBody'))
module_definition.setParseAction(annotate('ModuleDefinition'))
extension_marker.setParseAction(annotate('ExtensionMarker'))
name_form.setParseAction(annotate('NameForm'))
number_form.setParseAction(annotate('NumberForm'))
name_and_number_form.setParseAction(annotate('NameAndNumberForm'))
object_identifier_value.setParseAction(annotate('ObjectIdentifierValue'))
definitive_identifier.setParseAction(annotate('DefinitiveIdentifier'))
definitive_number_form.setParseAction(annotate('DefinitiveNumberForm'))
definitive_name_and_number_form.setParseAction(annotate('DefinitiveNameAndNumberForm'))
imports.setParseAction(annotate('Imports'))
exports.setParseAction(annotate('Exports'))
assignment_list.setParseAction(annotate('AssignmentList'))
bstring.setParseAction(annotate('BinaryStringValue'))
hstring.setParseAction(annotate('HexStringValue'))
start = OneOrMore(module_definition)
return start
示例15: Word
# 需要导入模块: from pyparsing import Suppress [as 别名]
# 或者: from pyparsing.Suppress import setParseAction [as 别名]
attr = Word(string.ascii_letters,
string.ascii_letters + string.digits + ';-',)
attr.leaveWhitespace()
attr.setName('attr')
hexdigits = Word(string.hexdigits, exact=2)
hexdigits.setName('hexdigits')
escaped = Suppress(Literal('\\')) + hexdigits
escaped.setName('escaped')
def _p_escaped(s, l, t):
text = t[0]
return chr(int(text, 16))
escaped.setParseAction(_p_escaped)
value = Combine(OneOrMore(CharsNotIn('*()\\\0') | escaped))
value.setName('value')
equal = Literal("=")
equal.setParseAction(lambda s, l, t: pureldap.LDAPFilter_equalityMatch)
approx = Literal("~=")
approx.setParseAction(lambda s, l, t: pureldap.LDAPFilter_approxMatch)
greater = Literal(">=")
greater.setParseAction(lambda s, l, t: pureldap.LDAPFilter_greaterOrEqual)
less = Literal("<=")
less.setParseAction(lambda s, l, t: pureldap.LDAPFilter_lessOrEqual)
filtertype = equal | approx | greater | less
filtertype.setName('filtertype')
simple = attr + filtertype + value
simple.leaveWhitespace()
simple.setName('simple')