本文整理汇总了Python中pyparsing.Keyword.setParseAction方法的典型用法代码示例。如果您正苦于以下问题:Python Keyword.setParseAction方法的具体用法?Python Keyword.setParseAction怎么用?Python Keyword.setParseAction使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Keyword
的用法示例。
在下文中一共展示了Keyword.setParseAction方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __createGram
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword 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()
示例2: np
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def np(words, fn = gr_opt_quoted_string, action=None):
p = Keyword(words[0], caseless=True)
for w in words[1:]:
p = p | Keyword(w, caseless=True)
p = p + gr_eq + fn
p.setParseAction(action)
return p
示例3: np
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def np(words, fn = gr_opt_quoted_string, action=nullDebugAction):
p = Keyword(words[0], caseless=True).setDebug(bacula_tools.DEBUG)
for w in words[1:]:
p = p | Keyword(w, caseless=True).setDebug(bacula_tools.DEBUG)
p = p + gr_eq + fn
p.setParseAction(action)
return p
示例4: parse
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword 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
示例5: build_parser
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def build_parser(root_directory, path, fake_root=os.getcwd(), file_reader=None):
from pyparsing import nestedExpr
from pyparsing import QuotedString
from pyparsing import Group
from pyparsing import restOfLine
from pyparsing import Word
from pyparsing import alphanums
from pyparsing import cStyleComment
from pyparsing import OneOrMore
from pyparsing import ZeroOrMore
from pyparsing import Optional
from pyparsing import Forward
from pyparsing import Literal
from pyparsing import Keyword
root = Forward()
include_handler = IncludeHandler(
root_directory,
path,
root,
fake_root=fake_root,
file_reader=file_reader)
# relaxed grammar
identifier = Word(alphanums + "-_.:/")
comment = ("//" + restOfLine).suppress() \
| ("#" + restOfLine).suppress() \
| cStyleComment
endstmt = Literal(";").suppress()
argument = QuotedString('"') \
| identifier
arguments = ZeroOrMore(argument)
statements = Forward()
section = nestedExpr("{", "}", statements)
include = Keyword("include").suppress() + QuotedString('"')
regular = identifier + Group(arguments) + Optional(section, default=[])
statement = include.setParseAction(include_handler.pyparsing_call) \
| regular.setParseAction(include_handler.pyparsing_mark)
statements << OneOrMore(statement + endstmt)
root << Optional(statements)
root.ignore(comment)
setattr(
root, 'parse_file',
lambda f, root=root: root.parseFile(f, parseAll=True))
return root
示例6: parse_string
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def parse_string(self, string):
'''Populate a new object from a string.
Parsing is hard, so we're going to call out to the pyparsing
library here. I hope you installed it!
'''
from pyparsing import Suppress, Regex, quotedString, restOfLine, Keyword, nestedExpr, Group, OneOrMore, Word, Literal, alphanums, removeQuotes, replaceWith
gr_eq = Literal('=')
gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
gr_opt_quoted_string = gr_stripped_string | restOfLine
gr_name = Keyword('name', caseless=True) + gr_eq + gr_opt_quoted_string
gr_name.setParseAction(lambda x, y=self: y._set_name(x[2]))
gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))
gr_phrase = Group(OneOrMore(gr_stripped_string | Word(alphanums)) + gr_eq + gr_opt_quoted_string)
def np(words, fn = gr_opt_quoted_string, action=print):
p = Keyword(words[0], caseless=True)
for w in words[1:]:
p = p | Keyword(w, caseless=True)
p = p + gr_eq + fn
p.setParseAction(action)
return p
gr_ifsc = np(PList('Ignore File Set Changes'), gr_yn, action=self._parse_setter(IGNORECHANGES))
gr_evss = np(PList('Enable VSS'), gr_yn, action=self._parse_setter(VSSENABLED))
gr_i_option = Group(Keyword(OPTIONS, caseless=True) + nestedExpr('{','}', Regex('[^\}]+', re.MULTILINE)))
gr_e_option = gr_i_option.copy()
gr_i_file = gr_phrase.copy()
gr_e_file = gr_phrase.copy()
gr_inc = Keyword('include', caseless=True) + nestedExpr('{','}', OneOrMore(gr_i_option | gr_i_file))
gr_inc.addParseAction(self._parse_add_entry)
gr_exc = Keyword('exclude', caseless=True) + nestedExpr('{','}', OneOrMore(gr_e_option | gr_e_file))
gr_exc.addParseAction(self._parse_add_entry)
gr_res = OneOrMore(gr_name | gr_inc | gr_exc | gr_ifsc | gr_evss)
result = gr_res.parseString(string, parseAll=True)
return 'Fileset: ' + self[NAME]
示例7: parse
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword 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 )
# ( function ( <name> ... ) <expr> )
# ( <expr> <expr> ... )
# ( call/cc <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")
pNAMES = ZeroOrMore(pNAME)
pNAMES.setParseAction(lambda result: [result])
pINTEGER = Word("0123456789")
pINTEGER.setParseAction(lambda result: EValue(VInteger(int(result[0]))))
pBOOLEAN = Keyword("true") | Keyword("false")
pBOOLEAN.setParseAction(lambda result: EValue(VBoolean(result[0]=="true")))
pEXPR = Forward()
pEXPRS = ZeroOrMore(pEXPR)
pEXPRS.setParseAction(lambda result: [result])
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]))
pBINDINGS = ZeroOrMore(pBINDING)
pBINDINGS.setParseAction(lambda result: [ result ])
def makeLet (bindings,body):
params = [ param for (param,exp) in bindings ]
args = [ exp for (param,exp) in bindings ]
return ECall(EFunction(params,body),args)
pLET = "(" + Keyword("let") + "(" + pBINDINGS + ")" + pEXPR + ")"
pLET.setParseAction(lambda result: makeLet(result[3],result[5]))
pCALL = "(" + pEXPR + pEXPRS + ")"
pCALL.setParseAction(lambda result: ECall(result[1],result[2]))
pFUN = "(" + Keyword("function") + "(" + pNAMES + ")" + pEXPR + ")"
pFUN.setParseAction(lambda result: EFunction(result[3],result[5]))
pFUNrec = "(" + Keyword("function") + pNAME + "(" + pNAMES + ")" + pEXPR + ")"
pFUNrec.setParseAction(lambda result: EFunction(result[4],result[6],name=result[2]))
def makeDo (exprs):
result = exprs[-1]
for e in reversed(exprs[:-1]):
# space is not an allowed identifier in the syntax!
result = makeLet([(" ",e)],result)
return result
pDO = "(" + Keyword("do") + pEXPRS + ")"
pDO.setParseAction(lambda result: makeDo(result[2]))
def makeWhile (cond,body):
return makeLet([(" while",
EFunction([],EIf(cond,makeLet([(" ",body)],ECall(EId(" while"),[])),EValue(VNone())),name=" while"))],
ECall(EId(" while"),[]))
pWHILE = "(" + Keyword("while") + pEXPR + pEXPR + ")"
pWHILE.setParseAction(lambda result: makeWhile(result[2],result[3]))
pCALLCC = "(" + Keyword("call/cc") + pEXPR + ")"
pCALLCC.setParseAction(lambda result: ECallCC(result[2]))
pEXPR << (pINTEGER | pBOOLEAN | pIDENTIFIER | pIF | pLET | pFUN | pFUNrec| pDO | pWHILE | pCALLCC | pCALL)
# can't attach a parse action to pEXPR because of recursion, so let's duplicate the parser
pTOPEXPR = pEXPR.copy()
pTOPEXPR.setParseAction(lambda result: {"result":"expression","expr":result[0]})
pDEFINE = "(" + Keyword("define") + pNAME + pEXPR + ")"
pDEFINE.setParseAction(lambda result: {"result":"value",
"name":result[2],
"expr":result[3]})
pDEFUN = "(" + Keyword("defun") + pNAME + "(" + pNAMES + ")" + pEXPR + ")"
pDEFUN.setParseAction(lambda result: {"result":"function",
"name":result[2],
#.........这里部分代码省略.........
示例8: Keyword
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
doftype = Keyword("x")|Keyword("y")|Keyword("z")|Keyword("angle_x")|Keyword("angle_y")|Keyword("angle_z")
dof = (doftype+Optional(paren+real+paren))
dofs = Keyword("set_dof")+tag+OneOrMore(dof )
jgroup = Keyword("set_jump_group")+tag+OneOrMore(tag)
symline = (sname|eline|anchor|vcoords|connect|dofs |jgroup)+LineEnd()
symfile = ZeroOrMore(symline)+StringEnd()
real .setParseAction( lambda s,l,t: float(t[0]) )
sname .setParseAction(tuple)
anchor .setParseAction(tuple)
efirst .setParseAction(lambda s,l,t: (t[0],t[2]))
erest .setParseAction(lambda s,l,t: ( t[1],t[4],t[6]))
eline .setParseAction(lambda s,l,t: ('E',tuple(t[2:])))
vcoord .setParseAction(lambda s,l,t: tuple(t[1:]))
vcoords.setParseAction(lambda s,l,t: ('xyz',tuple(t[1:-1])))
subunit.setParseAction(lambda s,l,t: ("subunit",t[1:]))
connect.setParseAction(lambda s,l,t: ("connect",tuple([x for x in t[1:] if not x=='\n'])))
dof .setParseAction(lambda s,l,t: ('dof',(t[0],t[2]) if len(t)>2 else (t[0],)))
dofs .setParseAction(lambda s,l,t: ('dofs',tuple(t[1:])))
jgroup .setParseAction(lambda s,l,t: ('jump_group',t[1:]))
symline.setParseAction(lambda s,l,t: tuple([x for x in t if not x=='\n']))
print dof .parseString("x(20.4244497891662)")
print dof .parseString("angle_x")
print dofs .parseString("set_dof JUMP0_0_to_com x(20.4244497891662)")
#print dofs .parseString("set_dof JUMP0_0_to_subunit angle_x angle_y angle_z")
#print dofs .parseString("set_dof JUMP0_0 x(3.81281197834553) angle_x")
# print connect.parseString("connect_virtual JUMP0_0_to_com VRT0_0 VRT0_0_base")
# print connect.parseString("connect_virtual JUMP0_0_to_subunit TEST SUBUNIT")
示例9: import
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
import re
from pyparsing import (
Word, Keyword, NotAny, alphanums, nums, alphas, OneOrMore, srange,
ZeroOrMore, Regex
)
from whispy_lispy import ast
int_literal = Word(nums) + NotAny('.')
int_literal.setParseAction(ast.Int.from_parsed_result)
float_literal = Word(nums) + Word('.') + Word(nums)
float_literal.setParseAction(ast.Float.from_parsed_result)
bool_literal = Keyword('#t') | Keyword('#f')
bool_literal.setParseAction(ast.Bool.from_parsed_result)
string_literal = Regex(r'\".*?(?<!\\)\"', re.DOTALL)
string_literal.setParseAction(ast.String.from_parse_result)
grammar = OneOrMore(float_literal | int_literal | bool_literal | string_literal)
示例10: Optional
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
istart = orig_test.setResultsName('istart')
eqsign = p.Literal('=').setParseAction(lambda s,loc,toks: [' = '])
comma = p.Literal(',').setParseAction(lambda s,loc,toks: [', '])
iend = orig_test.setResultsName('iend')
istep = orig_test.setResultsName('istep')
do_stmt = do_kwd + ivar + eqsign + istart + comma + iend + Optional(comma + istep)\
+ EOLL
do_stmt.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'enddo'])
if_expr = (Suppress('(') + orig_test + Suppress(')')) | orig_test
if_expr.setParseAction(lambda s,loc,toks: [' (' + ''.join(toks) + ')' ])
if_expr_2 = if_expr.copy()
if_expr_2.setParseAction(lambda s,loc,toks: [' (' + ''.join(toks) + ')' + ' then' ])
if_stmt = Keyword('if') + if_expr_2 + Optional(Suppress('then')) + EOLL
if_stmt.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'endif'])
elseif_stmt = Keyword('elseif') + if_expr_2 + Optional(Suppress('then')) + EOLL
elseif_stmt.setParseAction(lambda s,loc,toks: [''.join(toks), ''])
while_kwd = Keyword('while').setParseAction(lambda s,loc,toks: [' while'])
dowhile_stmt = Keyword('do') + while_kwd + if_expr + EOLL
dowhile_stmt.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'enddo'])
selectcase_kwd = Keyword('select') + Keyword('case')
selectcase_kwd.setParseAction(lambda s,loc,toks: [' '.join(toks)])
selectcase_stmt = selectcase_kwd + if_expr + EOLL
selectcase_stmt.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'end select'])
where_stmt = Keyword('where') + if_expr + EOLL
where_stmt.setParseAction(lambda s,loc,toks: [''.join(toks), '', 'end where'])
示例11: init_grammar
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def init_grammar(self):
"""Set up the parsing classes
Any changes to the grammar of the config file be done here.
"""
# Some syntax that we need, but don't bother looking at
SEMICOLON = (Suppress(";"))
EQUALS = Suppress("=")
OPENB = Suppress("(")
CLOSEB = Suppress(")")
BACKSLASH = Suppress("\\")
DASH = Suppress("-")
# Top Section
FILENAME = Word(alphas + nums + '-_.')
alignmentdef = Keyword('alignment') + EQUALS + FILENAME + SEMICOLON
alignmentdef.setParseAction(self.set_alignment)
treedef = Keyword('user_tree_topology') + EQUALS + FILENAME + SEMICOLON
treedef.setParseAction(self.set_user_tree)
def simple_option(name):
opt = Keyword(name) + EQUALS + Word(alphas + nums + '-_') + SEMICOLON
opt.setParseAction(self.set_simple_option)
return opt
branchdef = simple_option('branchlengths')
MODELNAME = Word(alphas + nums + '+')
modellist = delimitedList(MODELNAME)
modeldef = Keyword("models") + EQUALS + Group(
(
CaselessKeyword("all") | CaselessKeyword("mrbayes") | CaselessKeyword("raxml") |
CaselessKeyword("beast") | CaselessKeyword("all_protein") |
CaselessKeyword(
"all_protein_gamma") | CaselessKeyword("all_protein_gammaI")
)("predefined") |
Group(modellist)("userlist")) + SEMICOLON
modeldef.setParseAction(self.set_models)
modseldef = simple_option("model_selection")
topsection = alignmentdef + Optional(treedef) + branchdef + \
modeldef + modseldef
# Partition Parsing
column = Word(nums)
partname = Word(alphas + '_-' + nums)
partdef = column("start") +\
Optional(DASH + column("end")) +\
Optional(BACKSLASH + column("step"))
partdef.setParseAction(self.define_range)
partdeflist = Group(OneOrMore(Group(partdef)))
partition = Optional("charset") + partname("name") + \
EQUALS + partdeflist("parts") + SEMICOLON
partition.setParseAction(self.define_partition)
partlist = OneOrMore(Group(partition))
partsection = Suppress("[data_blocks]") + partlist
# Scheme Parsing
schemename = Word(alphas + '_-' + nums)
partnameref = partname.copy(
) # Make a copy, cos we set a different action on it
partnameref.setParseAction(self.check_part_exists)
subset = Group(OPENB + delimitedList(partnameref("name")) + CLOSEB)
subset.setParseAction(self.define_subset)
scheme = Group(OneOrMore(subset))
schemedef = schemename("name") + \
EQUALS + scheme("scheme") + SEMICOLON
schemedef.setParseAction(self.define_schema)
schemelist = OneOrMore(Group(schemedef))
schemealgo = simple_option("search")
schemesection = \
Suppress("[schemes]") + schemealgo + Optional(schemelist)
# We've defined the grammar for each section. Here we just put it all together
self.config_parser = (
topsection + partsection + schemesection + stringEnd)
示例12: simple_option
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def simple_option(name):
opt = Keyword(name) + EQUALS +\
Word(alphas + nums + '-_') + SEMICOLON
opt.setParseAction(self.set_simple_option)
return opt
示例13: SPICE_BNF
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def SPICE_BNF():
global bnf
if not bnf:
# punctuation
colon = Literal(":").suppress()
lbrace = Literal("{").suppress()
rbrace = Literal("}").suppress()
lbrack = Literal("[").suppress()
rbrack = Literal("]").suppress()
lparen = Literal("(").suppress()
rparen = Literal(")").suppress()
equals = Literal("=").suppress()
comma = Literal(",").suppress()
semi = Literal(";").suppress()
# primitive types
int8_ = Keyword("int8").setParseAction(replaceWith(ptypes.int8))
uint8_ = Keyword("uint8").setParseAction(replaceWith(ptypes.uint8))
int16_ = Keyword("int16").setParseAction(replaceWith(ptypes.int16))
uint16_ = Keyword("uint16").setParseAction(replaceWith(ptypes.uint16))
int32_ = Keyword("int32").setParseAction(replaceWith(ptypes.int32))
uint32_ = Keyword("uint32").setParseAction(replaceWith(ptypes.uint32))
int64_ = Keyword("int64").setParseAction(replaceWith(ptypes.int64))
uint64_ = Keyword("uint64").setParseAction(replaceWith(ptypes.uint64))
# keywords
enum32_ = Keyword("enum32").setParseAction(replaceWith(32))
enum16_ = Keyword("enum16").setParseAction(replaceWith(16))
enum8_ = Keyword("enum8").setParseAction(replaceWith(8))
flags32_ = Keyword("flags32").setParseAction(replaceWith(32))
flags16_ = Keyword("flags16").setParseAction(replaceWith(16))
flags8_ = Keyword("flags8").setParseAction(replaceWith(8))
channel_ = Keyword("channel")
server_ = Keyword("server")
client_ = Keyword("client")
protocol_ = Keyword("protocol")
typedef_ = Keyword("typedef")
struct_ = Keyword("struct")
message_ = Keyword("message")
image_size_ = Keyword("image_size")
bytes_ = Keyword("bytes")
cstring_ = Keyword("cstring")
switch_ = Keyword("switch")
default_ = Keyword("default")
case_ = Keyword("case")
identifier = Word(alphas, alphanums + "_")
enumname = Word(alphanums + "_")
integer = (
(Combine(CaselessLiteral("0x") + Word(nums + "abcdefABCDEF")) | Word(nums + "+-", nums))
.setName("int")
.setParseAction(cvtInt)
)
typename = identifier.copy().setParseAction(lambda toks: ptypes.TypeRef(str(toks[0])))
# This is just normal "types", i.e. not channels or messages
typeSpec = Forward()
attributeValue = integer ^ identifier
attribute = Group(Combine("@" + identifier) + Optional(lparen + delimitedList(attributeValue) + rparen))
attributes = Group(ZeroOrMore(attribute))
arraySizeSpecImage = Group(image_size_ + lparen + integer + comma + identifier + comma + identifier + rparen)
arraySizeSpecBytes = Group(bytes_ + lparen + identifier + comma + identifier + rparen)
arraySizeSpecCString = Group(cstring_ + lparen + rparen)
arraySizeSpec = (
lbrack
+ Optional(
identifier ^ integer ^ arraySizeSpecImage ^ arraySizeSpecBytes ^ arraySizeSpecCString, default=""
)
+ rbrack
)
variableDef = Group(
typeSpec
+ Optional("*", default=None)
+ identifier
+ Optional(arraySizeSpec, default=None)
+ attributes
- semi
).setParseAction(parseVariableDef)
switchCase = Group(
Group(
OneOrMore(
default_.setParseAction(replaceWith(None)) + colon
| Group(case_.suppress() + Optional("!", default="") + identifier) + colon
)
)
+ variableDef
).setParseAction(lambda toks: ptypes.SwitchCase(toks[0][0], toks[0][1]))
switchBody = Group(
switch_
+ lparen
+ delimitedList(identifier, delim=".", combine=True)
+ rparen
+ lbrace
+ Group(OneOrMore(switchCase))
#.........这里部分代码省略.........
示例14: parse_morphology
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
def parse_morphology(filename, filename_toparse):
global current_section_name
current_section_name = ''
converted_file = open(filename, 'w')
put_string = 'from neuron import h\ndef shape_3D(self):\n'
converted_file.write(put_string)
ntabs = 1 # from here on, add a tab to all lines
# define lists of characters for a..z and 1..9
uppercase = lowercase.upper()
lowercaseplus = lowercase+('_')
lowercaseplus = lowercaseplus+(uppercase)
nonzero = ''.join([str(i) for i in range(1, 10)])
COMMA = Literal(',')
EQUALS = Literal('=')
MINUS = Literal('-')
PERIOD = Literal('.')
LCURL = Literal('{')
RCURL = Literal('}')
LBRACK = Literal('(')
RBRACK = Literal(')')
LSQUARE = Literal('[')
RSQUARE = Literal(']')
PTSCLEAR = Literal('{pt3dclear()').suppress()
PTSCLEARNL = Literal('{\npt3dclear()\n').suppress()
integer = Word(nums)
single_section = Word(lowercaseplus, min = 2)
single_section.setResultsName('SINGLE')
integer_var = Word(lowercase, exact = 1)
double = Group(Optional(MINUS) + integer + Optional(PERIOD + integer))
operand = integer ^ integer_var
operator = Word('+-*/', exact=1)
unaryoperation = operand
binaryoperation = operand + operator + operand
operation = unaryoperation ^ binaryoperation
array_section = Group(single_section + LSQUARE.suppress() + operation + RSQUARE.suppress())
array_section.setResultsName('ARRAY')
section = single_section ^ array_section
section_location = Group(section + LBRACK.suppress() + double + RBRACK.suppress())
create = Keyword('create').suppress() + section + ZeroOrMore(COMMA.suppress() + section)
create.setParseAction(print_create(converted_file, ntabs))
connect = Keyword('connect').suppress() + section_location + COMMA.suppress() + section_location
connect.setParseAction(print_connect(converted_file, ntabs))
for_loop = Keyword('for').suppress() + integer_var + EQUALS.suppress() + integer + COMMA.suppress() + integer
# NOTE TO FUTURE SELF: for loops can only have one line of code in this implementation
for_loop.setParseAction(print_for_loop(converted_file, ntabs))
point_add = Literal('pt3dadd(').suppress() + double + COMMA.suppress() + double + COMMA.suppress() + double + COMMA.suppress() + double + RBRACK.suppress()
point_add.setParseAction(print_point_add(converted_file, ntabs))
point_style = Literal('pt3dstyle(').suppress() + double + COMMA.suppress() + double + COMMA.suppress() + double + COMMA.suppress() + double + RBRACK.suppress()
point_style.setParseAction(print_point_style(converted_file, ntabs))
geom_define_pre = section + (PTSCLEAR ^ PTSCLEARNL)
geom_define_body = OneOrMore(point_add ^ point_style) + RCURL.suppress()
geom_define_pre.setParseAction(update_current_section(converted_file, ntabs))
geom_define = geom_define_pre + geom_define_body
expression = (connect ^ for_loop ^ geom_define ^ create)
codeblock = OneOrMore(expression)
test_str = 'Ia_node[0] {\npt3dclear()\n pt3dadd( 47, 76, 92.5, 3.6) }'
#file_to_parse = open('../../tempdata/Ia_geometry')
file_to_parse = open(filename_toparse)
tokens = codeblock.parseString(file_to_parse.read())
示例15: __str__
# 需要导入模块: from pyparsing import Keyword [as 别名]
# 或者: from pyparsing.Keyword import setParseAction [as 别名]
" def __str__(self):",
" return self.__class__.__name__",
" def next_state(self):",
" return self._next_state_class()" ])
# define all state classes
statedef.extend(
"class %s(%s): pass" % (s,baseStateClass)
for s in states )
statedef.extend(
"%s._next_state_class = %s" % (s,fromTo[s])
for s in states if s in fromTo )
return indent + ("\n"+indent).join(statedef)+"\n"
stateMachine.setParseAction(expand_state_definition)
def expand_named_state_definition(source,loc,tokens):
indent = " " * (col(loc,source)-1)
statedef = []
# build list of states and transitions
states = set()
transitions = set()
baseStateClass = tokens.name + "State"
fromTo = {}
for tn in tokens.transitions:
states.add(tn.fromState)
states.add(tn.toState)
transitions.add(tn.transition)