本文整理汇总了Python中pyparsing.Word.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Word.setParseAction方法的具体用法?Python Word.setParseAction怎么用?Python Word.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Word
的用法示例。
在下文中一共展示了Word.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ImportFromString
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def ImportFromString(self, text):
#alphabet + number + underbar
nameG = Word( srange("[a-zA-Z_]"), srange("[a-zA-Z0-9_]") )
stringDoubleG = Literal('"') + SkipTo('"') + Literal('"')
stringSingleG = Literal("'") + SkipTo("'") + Literal("'")
stringG = stringDoubleG | stringSingleG
#comment
comment = (Literal('/*').suppress() + SkipTo('*/').suppress() + Literal('*/').suppress())
digraphNameG = Word( srange("[a-zA-Z_]"), srange("[a-zA-Z0-9_]") )
digraphNameG.setParseAction( self.DigraphNameAction )
nodeNameG = Word( srange("[a-zA-Z_]"), srange("[a-zA-Z0-9_]") )
nodeNameG.setParseAction( self.NodeNameAction )
startG = Literal('digraph').suppress() + digraphNameG.suppress() + Literal('{').suppress()
endG = Literal('}').suppress()
attrBaseG = nameG+Literal('=').suppress()+(nameG ^ stringG)
attrBaseG.setParseAction( self.AttributeAction )
attrRepeatG = attrBaseG + ZeroOrMore( Literal(',').suppress() + attrBaseG )
attrG = ZeroOrMore( Literal('[').suppress() + ZeroOrMore( attrRepeatG ) + Literal(']').suppress() )
nodeG = nodeNameG + attrG
edgeNameG = nameG + Literal('->').suppress() + nameG
edgeNameG.setParseAction( self.EdgeNameAction )
edgeG = edgeNameG + attrG
sizeG = Literal('size') + Literal('=') + (quotedString | dblQuotedString)
baseG = (sizeG | (nodeG ^ edgeG)) + Literal(';').suppress()
baseG = baseG | comment
baseG = ZeroOrMore(baseG)
grammerG = startG + baseG + endG
grammerG.parseString(text)
示例2: _define_valued_characters_section
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def _define_valued_characters_section(self, heading, characters,
parse_action, character_type):
"""Returns a parser object for a section specifying characters
and their valued features.
:param heading: section heading
:type heading: `str`
:param characters: valid characters
:type characters: `list` of `str`
:param parse_action: parse action for a character
:type parse_action: `function`
:param character_type: type of characters being described
:type character_type: `str`
"""
heading = Literal('[{}]'.format(heading))
character = Word(''.join(characters), exact=1).setResultsName(
'character')
character.setParseAction(self._handle_character)
feature = Word(alphas).setResultsName('feature')
feature.setParseAction(parse_action)
value = Literal('+') ^ Literal('-') ^ Literal('\N{MINUS SIGN}')
value.setParseAction(self._handle_feature_value)
feature_value = Group(value + feature)
feature_values = Group(delimitedList(feature_value))
character_definition = Dict(Group(character + Suppress(':') +
feature_values))
character_definitions = Group(OneOrMore(character_definition)).setResultsName(character_type)
section = Suppress(heading) + character_definitions
return section
示例3: __createGram
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def __createGram(self):
if self.notNeedSpace:
lNot = Keyword(self.operators['not'])
else:
lNot = Literal(self.operators['not'])
lAnd = Literal(self.operators['and'])
lOr = Literal(self.operators['or'])
lImp = Literal(self.operators['impL'])
lEqu = Literal(self.operators['equ'])
lTrue = Keyword(self.constants['true'])
lFalse = Keyword(self.constants['false'])
lVar = Word(alphas, alphanums+'_')
lVar.setParseAction(self.ffactory.createLogicVariable)
lTrue.setParseAction(self.ffactory.createLogicTruth)
lFalse.setParseAction(self.ffactory.createLogicFalse)
factor = lTrue | lFalse | lVar
expression = myparsing.operatorPrecedence(factor,
[
(lNot, 1, opAssoc.RIGHT, self.ffactory.createNotOperation),
(lAnd, 2, opAssoc.LEFT, self.ffactory.createAndOperation),
(lOr, 2, opAssoc.LEFT, self.ffactory.createOrOperation),
(lImp, 2, opAssoc.LEFT, self.ffactory.createImpicationOperation),
(lEqu, 2, opAssoc.LEFT, self.ffactory.createEquvalenceOperation)
],
[('(', ')'), ('[', ']'), ('{', '}')])
self.final = expression + StringEnd()
示例4: _construct_grammar
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def _construct_grammar():
logical_operator = get_logical_operator()
logical_expression = get_logical_expression()
facets_expression = get_facet_expression()
highlight_expression = get_highlight_expression()
sort_expression = get_sort_expression()
aggs_expression = get_aggregations_expression()
nested_expression = get_nested_expression()
# The below line describes how the type expression should be.
type_expression = Word('type')\
+ Word(':').suppress()\
+ Word(srange("[a-zA-Z0-9_]"))\
+ Optional(CaselessLiteral('AND')).suppress()
type_expression.setParseAction(parse_type_expression)
base_expression = Optional(highlight_expression)\
+ Optional(sort_expression)\
+ Optional(type_expression)\
+ ZeroOrMore(
(facets_expression
| aggs_expression
| nested_expression
| logical_expression)
+ Optional(logical_operator)
).setParseAction(parse_one_or_more_logical_expressions)
base_expression.setParseAction(parse_type_logical_facets_expression)
return base_expression
示例5: init_parser
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word 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)
示例6: _define_grammar
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def _define_grammar():
"""
Creates and returns a copy of the selector grammar.
Wrapped in a function to avoid polluting the module namespace.
"""
expr = Forward()
label_name = Word(LABEL_CHARS)
label_name.setParseAction(LabelNode)
string_literal = QuotedString('"') | QuotedString("'")
string_literal.setParseAction(LiteralNode)
set_literal = (Suppress("{") +
delimitedList(QuotedString('"') | QuotedString("'"), ",") +
Suppress("}"))
set_literal.setParseAction(SetLiteralNode)
eq_comparison = label_name + Suppress("==") + string_literal
eq_comparison.setParseAction(LabelToLiteralEqualityNode)
not_eq_comparison = label_name + Suppress("!=") + string_literal
not_eq_comparison.setParseAction(InequalityNode)
in_comparison = label_name + Suppress(Keyword("in")) + set_literal
in_comparison.setParseAction(LabelInSetLiteralNode)
not_in = Suppress(Keyword("not") + Keyword("in"))
not_in_comparison = label_name + not_in + set_literal
not_in_comparison.setParseAction(NotInNode)
has_check = (Suppress("has(") +
Word(LABEL_CHARS) +
Suppress(")"))
has_check.setParseAction(HasNode)
comparison = (eq_comparison |
not_eq_comparison |
in_comparison |
not_in_comparison |
has_check)
paren_expr = (Suppress("(") + expr + Suppress(")"))
value = comparison | paren_expr
and_expr = value + ZeroOrMore(Suppress("&&") + value)
and_expr.setParseAction(simplify_and_node)
or_expr = and_expr + ZeroOrMore(Suppress("||") + and_expr)
or_expr.setParseAction(simplify_or_node)
expr << or_expr
grammar = expr + StringEnd()
return grammar
示例7: get_highlight_expression
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def get_highlight_expression():
field_expression = Word(srange("[a-zA-Z0-9_.*]"))
field_expression.setParseAction(parse_highlight_field_expression)
fields_expression = OneOrMore(
field_expression + Optional(',').suppress())
fields_expression.setParseAction(parse_highlight_expression)
highlight_expression = Word('highlight:').suppress() \
+ Word('[').suppress() \
+ fields_expression + Word(']').suppress()
return highlight_expression
示例8: setup
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word 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
示例9: eval_query
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def eval_query(query_str):
global WORD_CHARS
boolOperand = Word(WORD_CHARS)
boolOperand.setParseAction(BoolOperand)
boolExpr = infixNotation(
boolOperand,
[("not", 1, opAssoc.RIGHT, BoolNot), ("and", 2, opAssoc.LEFT, BoolAnd), ("or", 2, opAssoc.LEFT, BoolOr)],
)
return boolExpr.parseString(query_str.lower())[0].calcop()
示例10: __init__
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def __init__(self, EvaluateVariableChild=None, EvaluateNumberChild=None):
EvaluateVariableChild = EvaluateVariableChild or EvaluateVariable
EvaluateNumberChild = EvaluateNumberChild or EvaluateNumber
# what is a float number
floatNumber = Regex(r'[-]?\d+(\.\d*)?([eE][-+]?\d+)?')
# a variable is a combination of letters, numbers, and underscor
variable = Word(alphanums + "_")
# a sign is plus or minus
signOp = oneOf('+ -')
# an operand is a variable or a floating point number
operand = floatNumber ^ variable
# when a floatNumber is found, parse it with evaluate number
floatNumber.setParseAction(EvaluateNumberChild)
# when a variable is found, parse it with the EvaluateVariableChild
# or EvaluateVariable
variable.setParseAction(EvaluateVariableChild)
# comparisons include lt,le,gt,ge,eq,ne
comparisonOp = oneOf("< <= > >= == !=")
# negation of the boolean is !
notOp = oneOf("!")
# an expression is a either a comparison or
# a NOT operation (where NOT a is essentially (a == False))
comparisonExpression = operatorPrecedence(operand,
[
(comparisonOp,
2,
opAssoc.LEFT,
EvaluateComparison
),
(notOp,
1,
opAssoc.RIGHT,
EvaluateNot
),
])
# boolean logic of AND or OR
boolOp = oneOf("& |")
# a bool expression contains a nested bool expression or a comparison,
# joined with a boolean operation
boolExpression = Forward()
boolPossible = boolExpression | comparisonExpression
self.boolExpression = operatorPrecedence(boolPossible,
[
(boolOp,
2,
opAssoc.RIGHT,
EvaluateOrAnd
),
])
return
示例11: main
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def main(s):
lpar = Literal('(').suppress()
rpar = Literal(')').suppress()
integer = Word(nums)
element = Word(alphas, exact=1)
formula = Forward()
term = Group((element | Group(lpar + formula + rpar)('subgroup')) +
Optional(integer, default=1)('mult'))
formula << OneOrMore(term)
integer.setParseAction(process_integer)
term.setParseAction(process_term)
formula.setParseAction(process_formula)
return formula.parseString(s)[0]
示例12: _define_base_characters_section
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def _define_base_characters_section (self):
heading = Literal('[Base Characters]')
character = Word(''.join(BASE_CHARACTERS), exact=1).setResultsName(
'character')
character.setParseAction(self._handle_character)
feature = Word(alphas).setResultsName('feature')
feature.setParseAction(self._handle_character_base_feature)
features = delimitedList(feature)
character_definition = Group(character + Suppress(':') + \
Optional(features))
character_definitions = Group(OneOrMore(character_definition)).setResultsName('base_characters')
section = Suppress(heading) + character_definitions
return section
示例13: parse
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def parse (input):
# parse a string into an element of the abstract representation
# Grammar:
#
# <expr> ::= <integer>
# true
# false
# <identifier>
# ( if <expr> <expr> <expr> )
# ( let ( ( <name> <expr> ) ) <expr )
# ( + <expr> <expr> )
# ( * <expr> <expr> )
#
idChars = alphas+"_+*-?!=<>"
pIDENTIFIER = Word(idChars, idChars+"0123456789")
pIDENTIFIER.setParseAction(lambda result: EId(result[0]))
# A name is like an identifier but it does not return an EId...
pNAME = Word(idChars,idChars+"0123456789")
pINTEGER = Word("-0123456789","0123456789")
pINTEGER.setParseAction(lambda result: EInteger(int(result[0])))
pBOOLEAN = Keyword("true") | Keyword("false")
pBOOLEAN.setParseAction(lambda result: EBoolean(result[0]=="true"))
pEXPR = Forward()
pIF = "(" + Keyword("if") + pEXPR + pEXPR + pEXPR + ")"
pIF.setParseAction(lambda result: EIf(result[2],result[3],result[4]))
pBINDING = "(" + pNAME + pEXPR + ")"
pBINDING.setParseAction(lambda result: (result[1],result[2]))
pLET = "(" + Keyword("let") + "(" + pBINDING + ")" + pEXPR + ")"
pLET.setParseAction(lambda result: ELet([result[3]],result[5]))
pPLUS = "(" + Keyword("+") + pEXPR + pEXPR + ")"
pPLUS.setParseAction(lambda result: ECall("+",[result[2],result[3]]))
pTIMES = "(" + Keyword("*") + pEXPR + pEXPR + ")"
pTIMES.setParseAction(lambda result: ECall("*",[result[2],result[3]]))
pEXPR << (pINTEGER | pBOOLEAN | pIDENTIFIER | pIF | pLET | pPLUS | pTIMES)
result = pEXPR.parseString(input)[0]
return result # the first element of the result is the expression
示例14: create_parser
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
def create_parser():
"""Creates the parser using PyParsing functions."""
# Day details (day number, superscript and day name)
daynum = Word(nums, max=2)
superscript = oneOf("th rd st nd", caseless=True)
day = oneOf("Mon Monday Tue Tues Tuesday Wed Weds Wednesday "
"Thu Thur Thurs Thursday Fri Friday Sat Saturday Sun Sunday", caseless=True)
full_day_string = daynum + Optional(superscript).suppress()
full_day_string.setParseAction(check_day)
full_day_string.leaveWhitespace()
# Month names, with abbreviations, with action to convert to equivalent month number
month = oneOf(list(MONTHS.keys()), caseless=True) + \
Optional(Literal(".").suppress())
month.setParseAction(month_to_number)
# Year
year = Word(nums, exact=4)
year.setParseAction(lambda tokens: int(tokens[0]))
time_sep = oneOf(": .")
am_pm = oneOf("am pm", caseless=True)
hours = Word(nums, max=2)
mins = Word(nums, max=2)
time = hours("hour") + time_sep.suppress() + \
mins("mins") + Optional(am_pm)("meridian")
# date pattern
date = (
Optional(time).suppress() & Optional(full_day_string("day")) & Optional(day).suppress() &
Optional(month("month")) & Optional(year("year"))
)
# Possible separators
separator = oneOf("- -- to until through till untill \u2013 \u2014 ->", caseless=True)
# Strings to completely ignore (whitespace ignored by default)
ignoreable_chars = oneOf(", from starting beginning of", caseless=True)
# Final putting together of everything
daterange = (
Optional(date("start") + Optional(time).suppress() + separator.suppress()) +
date("end") + Optional(time).suppress() + stringEnd()
)
daterange.ignore(ignoreable_chars)
return daterange
示例15: __init__
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import setParseAction [as 别名]
class NodeParser:
def __init__(self):
self.num = Word(nums)
self.header = Regex(r"^UCLA.*")
self.comment = Regex(r"#.*")
self.bkid = Word(alphanums)
self.num_nodes = Literal("NumNodes") + Literal(":") + self.num("NumNodes")
self.num_terminals = Literal("NumTerminals") + Literal(":") + self.num("NumTerminals")
self.size = Group(self.num("width") + self.num("height"))
self.terminal = Optional(Literal("terminal"))
self.node = self.bkid("id") + self.size("size") + self.terminal
self.node_grammar = (
self.header + ZeroOrMore(self.comment) + self.num_nodes + self.num_terminals + OneOrMore(self.node)
)
self.coordinate = Group(self.num("x") + self.num("y"))
self.pl = (
self.bkid("id") + self.coordinate("coordinate") + Suppress(Literal(": N") + Optional(Literal(r"/FIXED")))
)
self.pl_grammar = self.header + ZeroOrMore(self.comment) + OneOrMore(self.pl)
def compute_chip_size(self, benchmark):
benchmark_path = pathlib.Path(os.environ["BENCHMARK"])
node_file = benchmark_path / "ispd2005/{0}/{0}.nodes".format(benchmark)
pl_file = benchmark_path / "ispd2005/{0}/{0}.pl".format(benchmark)
print(node_file.as_posix())
print(pl_file.as_posix())
x_max = 0
y_max = 0
sizes = []
coordinates = []
self.size.setParseAction(lambda tokens: sizes.append([tokens.width, tokens.height]))
self.coordinate.setParseAction(lambda tokens: coordinates.append((tokens.x, tokens.y)))
self.bkid.setParseAction(lambda tokens: print(tokens[0]))
self.node_grammar.parseFile(node_file.as_posix())
self.pl_grammar.parseFile(pl_file.as_posix())
for i in range(len(sizes)):
print(i)
if coordinates[i][0] + sizes[i][0] > x_max:
x_max = coordinates[i][0] + sizes[i][0]
if coordinates[i][1] + sizes[i][1] > y_max:
y_max = coordinates[i][1] + sizes[i][1]
return x_max, y_max