本文整理汇总了Python中pyparsing.Suppress类的典型用法代码示例。如果您正苦于以下问题:Python Suppress类的具体用法?Python Suppress怎么用?Python Suppress使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Suppress类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: parse
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
开发者ID:gnovis,项目名称:swift,代码行数:35,代码来源:parser_fca.py
示例2: init_parser
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)
开发者ID:brettc,项目名称:tigger,代码行数:29,代码来源:alignment.py
示例3: parse_grd_file
def parse_grd_file(self):
global __line
try:
f = open(self.grd_file, 'r')
except:
raise
for j in range(0, 6):
__line = f.next()
(self.nx, self.ny) = map(int, __line.split())
print "Grid file %s (%d, %d)" % (self.grd_file, self.nx, self.ny)
f.close()
floatNumber = Regex(r'-?\d+(\.\d*)?([eE][\+-]\d+)?').setParseAction(lambda s, l, t: [float(t[0])])
integer = Word(nums).setParseAction(lambda s, l, t: [long(t[0])])
grdline = Suppress('ETA=') + Suppress(integer) + OneOrMore(floatNumber)
for a in grdline.searchString(file(self.grd_file).read()):
if len(self.x) < self.ny:
self.x.append(a.asList())
else:
self.y.append(a.asList())
开发者ID:mvrk,项目名称:BACKUP,代码行数:26,代码来源:models.py
示例4: parse
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
开发者ID:Zurgy,项目名称:DateParser,代码行数:27,代码来源:date_parser.py
示例5: main
def main():
filename = sys.argv[1]
source = open(filename).read()
commentFilter = Suppress( javaStyleComment ).ignore( dblQuotedString )
source = commentFilter.transformString(source)
source = source.replace('\r\n', '\n')
source = source.replace('\r', '')
for m in re.finditer('#pragma[ \t][ \t]*pskel.*\n', source):
pragma = m.group(0)
begin = m.start(0)
end = m.end(0)+1
while pragma.strip()[-1]=='\\':
pragma = pragma.strip()[:-1].strip()
tmp = ''
while source[end]!='\n':
tmp += source[end]
end += 1
pragma += ' '+tmp.strip()
end += 1
pragma = pragma.strip()
print begin, end
print pragma
#print source[begin:end]
pinfo = parsePragma(pragma)
print pinfo
fcall = readFuncCall(source,end)
print fcall
kfunc = findFunctionDef(source,fcall[0])
print source[fcall[2]:fcall[3]]
mainf = readOutterFunction(source, begin)
#print mainf
fcall_name = '_pskelcc_stencil_'+str(fcall[2])+'_'+str(fcall[3])
tmainf = mainf['src'].replace(source[begin:end],'\n').replace(source[fcall[2]:fcall[3]],fcall_name+'();')
print tmainf
parser = c_parser.CParser()
ast = parser.parse(tmainf)
pgen = PSkelGenerator(pinfo,fcall_name)
new_mainf = pgen.visit(ast)
parser = c_parser.CParser()
ast = parser.parse(kfunc['src'])
pgen = PSkelKernelGenerator(pinfo)
new_kfunc = pgen.visit(ast)
f = open(sys.argv[2],'w')
f.write('#define PSKEL_OMP\n')
if pinfo['device']=='gpu':
f.write('#define PSKEL_CUDA\n')
f.write('''
#include "include/PSkel.h"
using namespace PSkel;\n\n''')
f.write(source[:kfunc['begin']]+new_kfunc+source[kfunc['end']:mainf['begin']]+new_mainf+source[mainf['end']:])
f.close()
开发者ID:pskel,项目名称:benchmarks,代码行数:58,代码来源:pskelcc.py
示例6: setup
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
开发者ID:haystack,项目名称:eyebrowse-server,代码行数:55,代码来源:date_parser.py
示例7: getEbnfParser
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
开发者ID:AnotherTest,项目名称:DictatorBot,代码行数:31,代码来源:Command.py
示例8: parse_table
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
开发者ID:power-system-simulation-toolbox,项目名称:psst,代码行数:11,代码来源:case_parser.py
示例9: parse_puppetfile_forge_mods
def parse_puppetfile_forge_mods(cls, file_contents):
mod_kwargs = {}
quotedString = QuotedString('"') ^ QuotedString('\'')
forge_url_grammar = Suppress('forge') + quotedString
for url, in forge_url_grammar.searchString(file_contents):
mod_kwargs['forge_url'] = url
mod_grammar = Suppress('mod') + quotedString + Suppress(',') + quotedString
mods = mod_grammar.searchString(file_contents)
for mod, version in mods:
user, mod_name = mod.split('/')
yield cls(user, mod_name, version, **mod_kwargs)
开发者ID:mayflower,项目名称:pumuckl,代码行数:13,代码来源:module.py
示例10: __init__
def __init__(self):
self.ALPHA_LABEL = Regex(r'alpha\[\d+\]:')
self.LNL_LABEL = Literal('Final GAMMA-based Score of best tree')
self.FRQ_LABEL = Regex(r'Base frequencies: (?=\d+)') ^ Regex(r'ML estimate base freqs\[\d+\]:')
self.NAMES_LABEL = Regex(r'Partition: \d+ with name:\s+')
self.RATES_LABEL = Regex(r'rates\[\d+\].+?:')
self.MODEL_LABEL = Literal('Substitution Matrix:')
self.alpha = OneOrMore(Suppress(SkipTo(self.ALPHA_LABEL)) + Suppress(self.ALPHA_LABEL) + FLOAT)
self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + Suppress(self.LNL_LABEL) + FLOAT
self.frq = OneOrMore(Group(Suppress(SkipTo(self.FRQ_LABEL)) + Suppress(self.FRQ_LABEL) + OneOrMore(FLOAT)))
self.names = OneOrMore(Suppress(SkipTo(self.NAMES_LABEL)) + Suppress(self.NAMES_LABEL) + CharsNotIn('\n') + Suppress(LineEnd()))
self.rates = OneOrMore(Group(Suppress(SkipTo(self.RATES_LABEL)) + Suppress(self.RATES_LABEL) + OneOrMore(FLOAT)))
self.model = Suppress(SkipTo(self.MODEL_LABEL)) + Suppress(self.MODEL_LABEL) + WORD
MODEL_LABEL = Literal('Substitution Matrix:')
SCORE_LABEL = Literal('Final GAMMA likelihood:')
DESC_LABEL = Literal('Model Parameters of Partition')
NAME_LEADIN = Literal(', Name:')
DATATYPE_LEADIN = Literal(', Type of Data:')
ALPHA_LEADIN = Literal('alpha:')
TREELENGTH_LEADIN = Literal('Tree-Length:')
RATES_LABEL = Regex(r'rate \w <-> \w:')
FREQS_LABEL = Regex(r'freq pi\(\w\):')
BEST_LEADIN = Literal('Starting final GAMMA-based thorough Optimization on tree ')
PARTITION_LEADIN = Literal('Partition:')
INFERENCE_LEADIN = Literal('Inference[')
model = Suppress(SkipTo(MODEL_LABEL)) + Suppress(MODEL_LABEL) + WORD
likelihood = Suppress(SkipTo(SCORE_LABEL)) + Suppress(SCORE_LABEL) + FLOAT
description = (Suppress(SkipTo(DESC_LABEL)) +
Suppress(DESC_LABEL) + INT +
Suppress(NAME_LEADIN) +
SPACEDWORD +
Suppress(DATATYPE_LEADIN) +
WORD)
alpha = Suppress(ALPHA_LEADIN) + FLOAT
rates = Suppress(RATES_LABEL) + FLOAT
freqs = Suppress(FREQS_LABEL) + FLOAT
self.partition = OneOrMore(Suppress(SkipTo(PARTITION_LEADIN)) + Suppress(PARTITION_LEADIN) + INT)
self.inference = OneOrMore(Suppress(SkipTo(INFERENCE_LEADIN)) + Suppress(INFERENCE_LEADIN) + INT)
self.best = Suppress(SkipTo(BEST_LEADIN)) + Suppress(BEST_LEADIN) + INT
self._dash_f_e_parser = (Group(OneOrMore(model)) +
likelihood +
Group(OneOrMore(Group(description +
alpha +
Suppress(TREELENGTH_LEADIN) +
Suppress(FLOAT) +
Group(OneOrMore(rates)) +
Group(OneOrMore(freqs))
))))
开发者ID:kgori,项目名称:treeCl,代码行数:51,代码来源:parsers.py
示例11: parser
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
开发者ID:GunioRobot,项目名称:pycucumber,代码行数:48,代码来源:regex_parser.py
示例12: songs_pyparsing
def songs_pyparsing(fh):
r"""
>>> import os
>>> filename = os.path.dirname(__file__)
>>> filename = os.path.join(filename, "data/Various-Pop.m3u")
>>> with open(filename, "rt", encoding="utf8") as fh:
... songs = songs_pyparsing(fh)
>>> songs[0].title, songs[0].seconds, songs[0].filename
('Various - Two Tribes', 236, 'Various\\Frankie Goes To Hollywood\\02-Two Tribes.ogg')
>>> songs[-1].title, songs[-1].seconds, songs[-1].filename
('The Police - Walking On The Moon', 303, 'Various\\Sting & The Police 1997\\06-Walking On The Moon.ogg')
>>> lines = []
>>> lines.append("#EXTM3U")
>>> lines.append("#EXTINF:140,The Beatles - Love Me Do")
>>> lines.append("Beatles\\Greatest Hits\\01-Love Me Do.ogg")
>>> lines.append("#EXTINF:-1,The Beatles - From Me To You")
>>> lines.append("Beatles\\Greatest Hits\\02-From Me To You.ogg")
>>> import io
>>> data = io.StringIO("\n".join(lines))
>>> songs = songs_ply(data)
>>> len(songs) == 2
True
>>> songs[0].title, songs[0].seconds
('The Beatles - Love Me Do', 140)
>>> songs[1].title, songs[1].seconds
('The Beatles - From Me To You', -1)
"""
def add_song(tokens):
songs.append(Song(tokens.title, tokens.seconds,
tokens.filename))
#songs.append(Song(**tokens.asDict()))
songs = []
title = restOfLine("title")
filename = restOfLine("filename")
seconds = Combine(Optional("-") + Word(nums)).setParseAction(
lambda tokens: int(tokens[0]))("seconds")
info = Suppress("#EXTINF:") + seconds + Suppress(",") + title
entry = info + LineEnd() + filename + LineEnd()
entry.setParseAction(add_song)
parser = Suppress("#EXTM3U") + OneOrMore(entry)
try:
parser.parseFile(fh)
except ParseException as err:
print("parse error: {0}".format(err))
return []
return songs
开发者ID:178220709,项目名称:PyHello,代码行数:48,代码来源:ReadM3U.py
示例13: parse_issue
def parse_issue(issue):
"""Given an issue, return data that needs saving"""
from pyparsing import Word, Suppress, Literal, OneOrMore, Optional, nums, printables
sprint = (Literal('Sprint') | Literal('sprint')) + Word(nums)
points = Suppress(Literal('(')) + Word(nums) + Suppress(Literal(')'))
deadline = Suppress(Literal('<')) + Word(nums)
name = OneOrMore(Word(printables))
title = Optional(sprint).setResultsName("sprint") + \
Optional(name).setResultsName("name") + \
Optional(deadline).setResultsName("deadline") + \
points.setResultsName("points")
try:
_, r = title.parseString(issue['title'])
print r
except:
pass
开发者ID:alixedi,项目名称:bitburn,代码行数:16,代码来源:bit.py
示例14: __init__
def __init__(self):
self.ALPHA_LABEL = Regex(r"alpha\[\d+\]:")
self.LNL_LABEL = Literal("Final GAMMA-based Score of best tree")
self.FRQ_LABEL = Regex(r"Base frequencies: (?=\d+)") ^ Regex(r"ML estimate base freqs\[\d+\]:")
self.NAMES_LABEL = Regex(r"Partition: \d+ with name:\s+")
self.RATES_LABEL = Regex(r"rates\[\d+\].+?:")
self.MODEL_LABEL = Literal("Substitution Matrix:")
self.alpha = OneOrMore(Suppress(SkipTo(self.ALPHA_LABEL)) + Suppress(self.ALPHA_LABEL) + FLOAT)
self.lnl = Suppress(SkipTo(self.LNL_LABEL)) + Suppress(self.LNL_LABEL) + FLOAT
self.frq = OneOrMore(Group(Suppress(SkipTo(self.FRQ_LABEL)) + Suppress(self.FRQ_LABEL) + OneOrMore(FLOAT)))
self.names = OneOrMore(
Suppress(SkipTo(self.NAMES_LABEL)) + Suppress(self.NAMES_LABEL) + CharsNotIn("\n") + Suppress(LineEnd())
)
self.rates = OneOrMore(
Group(Suppress(SkipTo(self.RATES_LABEL)) + Suppress(self.RATES_LABEL) + OneOrMore(FLOAT))
)
self.model = Suppress(SkipTo(self.MODEL_LABEL)) + Suppress(self.MODEL_LABEL) + WORD
MODEL_LABEL = Literal("Substitution Matrix:")
SCORE_LABEL = Literal("Final GAMMA likelihood:")
DESC_LABEL = Literal("Model Parameters of Partition")
NAME_LEADIN = Literal(", Name:")
DATATYPE_LEADIN = Literal(", Type of Data:")
ALPHA_LEADIN = Literal("alpha:")
TREELENGTH_LEADIN = Literal("Tree-Length:")
RATES_LABEL = Regex(r"rate \w <-> \w:")
FREQS_LABEL = Regex(r"freq pi\(\w\):")
model = Suppress(SkipTo(MODEL_LABEL)) + Suppress(MODEL_LABEL) + WORD
likelihood = Suppress(SkipTo(SCORE_LABEL)) + Suppress(SCORE_LABEL) + FLOAT
description = (
Suppress(SkipTo(DESC_LABEL))
+ Suppress(DESC_LABEL)
+ INT
+ Suppress(NAME_LEADIN)
+ SPACEDWORD
+ Suppress(DATATYPE_LEADIN)
+ WORD
)
alpha = Suppress(ALPHA_LEADIN) + FLOAT
rates = Suppress(RATES_LABEL) + FLOAT
freqs = Suppress(FREQS_LABEL) + FLOAT
self._dash_f_e_parser = (
Group(OneOrMore(model))
+ likelihood
+ Group(
OneOrMore(
Group(
description
+ alpha
+ Suppress(TREELENGTH_LEADIN)
+ Suppress(FLOAT)
+ Group(OneOrMore(rates))
+ Group(OneOrMore(freqs))
)
)
)
)
开发者ID:DessimozLab,项目名称:treeCl,代码行数:59,代码来源:parsers.py
示例15: fromString
def fromString(inputText, verbose=False):
if verbose: print 'Verbose:', verbose
text = nestedExpr("/*", "*/").suppress().transformString(inputText)
semicolon = Suppress(Word(";"))
quote = Suppress(Word("\""))
op = Suppress(Word("{"))
cl = Suppress(Word("}"))
opp = Suppress(Word("("))
clp = Suppress(Word(")"))
lt = Suppress(Word("<"))
gt = Suppress(Word(">"))
identifier = Word(alphas+"_",alphanums+"_")
typeIdentifier = Word(alphas+"_",alphanums+"_:")
## Imports
idslImport = Suppress(Word("import")) + quote + CharsNotIn("\";").setResultsName('path') + quote + semicolon
idslImports = ZeroOrMore(idslImport)
dictionaryDef = Word("dictionary") + lt + CharsNotIn("<>;") + gt + identifier.setResultsName('name') + semicolon
sequenceDef = Word("sequence") + lt + CharsNotIn("<>;") + gt + identifier.setResultsName('name') + semicolon
enumDef = Word("enum") + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
structDef = Word("struct") + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
exceptionDef = Word("exception") + identifier.setResultsName('name') + op + CharsNotIn("{}") + cl + semicolon
raiseDef = Suppress(Word("throws")) + typeIdentifier + ZeroOrMore( Literal(',') + typeIdentifier )
decoratorDef = Literal('idempotent') | Literal('out')
retValDef = typeIdentifier.setResultsName('ret')
firstParam = Group( Optional(decoratorDef.setResultsName('decorator')) + typeIdentifier.setResultsName('type') + identifier.setResultsName('name'))
nextParam = Suppress(Word(',')) + firstParam
params = firstParam + ZeroOrMore(nextParam)
remoteMethodDef = Group(Optional(decoratorDef) + retValDef + typeIdentifier.setResultsName('name') + opp + Optional( params).setResultsName('params') + clp + Optional(raiseDef) + semicolon )
interfaceDef = Word("interface") + typeIdentifier.setResultsName('name') + op + Group(ZeroOrMore(remoteMethodDef)) + cl + semicolon
moduleContent = Group(structDef | enumDef | exceptionDef | dictionaryDef | sequenceDef | interfaceDef)
module = Suppress(Word("module")) + identifier.setResultsName("name") + op + ZeroOrMore(moduleContent).setResultsName("contents") + cl + semicolon
IDSL = idslImports.setResultsName("imports") + module.setResultsName("module")
IDSL.ignore( cppStyleComment )
tree = IDSL.parseString(text)
return IDSLParsing.module(tree)
开发者ID:BasilMVarghese,项目名称:robocomp,代码行数:46,代码来源:parseIDSL.py
示例16: detect_token
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)
'''
开发者ID:NSinopoli,项目名称:nephrite,代码行数:45,代码来源:parser.py
示例17: get_network_name
def get_network_name(self):
"""
Retruns the name of the network
Example
---------------
>>> from pgmpy.readwrite import BIFReader
>>> reader = BIF.BifReader("bif_test.bif")
>>> reader.network_name()
'Dog-Problem'
"""
start = self.network.find('network')
end = self.network.find('}\n', start)
# Creating a network attribute
network_attribute = Suppress('network') + Word(alphanums + '_' + '-') + '{'
network_name = network_attribute.searchString(self.network[start:end])[0][0]
return network_name
开发者ID:MariosRichards,项目名称:BES_analysis_code,代码行数:18,代码来源:BIF.py
示例18: parseReactions
def parseReactions(reaction):
name = Word(alphanums + '_-') + ':'
species = (Word(alphanums + "_:#-")
+ Suppress('()')) + ZeroOrMore(Suppress('+') + Word(alphanums + "_:#-")
+ Suppress("()"))
rate = Word(alphanums + "()")
grammar = Suppress(Optional(name)) + ((Group(species) | '0') + Suppress(Optional("<") + "->") +
(Group(species) | '0') + Suppress(rate)) \
^ (species + Suppress(Optional("<") + "->") + Suppress(rate))
result = grammar.parseString(reaction).asList()
if len(result) < 2:
result = [result, []]
if '<->' in reaction and len(result[0]) == 1 and len(result[1]) == 2:
result2 = [result[1], result[0]]
result = result2
return result
开发者ID:Alwnikrotikz,项目名称:bionetgen,代码行数:19,代码来源:moleculeCreation.py
示例19: __init__
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"
开发者ID:David-Bess,项目名称:medicare-demo,代码行数:42,代码来源:pysoc.py
示例20: fromString
def fromString(inputText, verbose=False):
if verbose: print 'Verbose:', verbose
text = nestedExpr("/*", "*/").suppress().transformString(inputText)
semicolon = Suppress(Word(";"))
quote = Suppress(Word("\""))
op = Suppress(Word("{"))
cl = Suppress(Word("}"))
opp = Suppress(Word("("))
clp = Suppress(Word(")"))
identifier = Word( alphas+"_", alphanums+"_" )
commIdentifier = Group(identifier.setResultsName('identifier') + Optional(opp + (CaselessLiteral("ice")|CaselessLiteral("ros")).setResultsName("type") + clp))
# Imports
idslImport = Suppress(CaselessLiteral("import")) + quote + CharsNotIn("\";").setResultsName('path') + quote + semicolon
idslImports = ZeroOrMore(idslImport)
# Communications
implementsList = Group(CaselessLiteral('implements') + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon)
requiresList = Group(CaselessLiteral('requires') + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon)
subscribesList = Group(CaselessLiteral('subscribesTo') + commIdentifier + ZeroOrMore(Suppress(Word(',')) + commIdentifier) + semicolon)
publishesList = Group(CaselessLiteral('publishes') + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon)
communicationList = implementsList | requiresList | subscribesList | publishesList
communications = Group( Suppress(CaselessLiteral("communications")) + op + ZeroOrMore(communicationList) + cl + semicolon)
# Language
language = Suppress(CaselessLiteral("language")) + (CaselessLiteral("cpp")|CaselessLiteral("python")) + semicolon
# GUI
gui = Group(Optional(Suppress(CaselessLiteral("gui")) + CaselessLiteral("Qt") + opp + identifier + clp + semicolon ))
# additional options
options = Group(Optional(Suppress(CaselessLiteral("options")) + identifier + ZeroOrMore(Suppress(Word(',')) + identifier) + semicolon))
componentContents = communications.setResultsName('communications') & language.setResultsName('language') & gui.setResultsName('gui') & options.setResultsName('options')
component = Suppress(CaselessLiteral("component")) + identifier.setResultsName("name") + op + componentContents.setResultsName("properties") + cl + semicolon
CDSL = idslImports.setResultsName("imports") + component.setResultsName("component")
CDSL.ignore( cppStyleComment )
tree = CDSL.parseString(text)
return CDSLParsing.component(tree)
开发者ID:soura97,项目名称:robocomp,代码行数:39,代码来源:parseCDSL.py
注:本文中的pyparsing.Suppress类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论