本文整理汇总了Python中pyparsing.Group.parseString方法的典型用法代码示例。如果您正苦于以下问题:Python Group.parseString方法的具体用法?Python Group.parseString怎么用?Python Group.parseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Group
的用法示例。
在下文中一共展示了Group.parseString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse(self, filename):
model = None
alpha = None
lnl = None
freq = None
rates = None
with open(filename) as fl:
s = fl.read()
try:
model, lnl, alpha = self.common.parseString(s).asList()
except ParseException as err:
logger.error(err)
if model == 'JC69':
freq = [0.25, 0.25, 0.25, 0.25]
rates = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
elif model == 'K80':
freq = [0.25, 0.25, 0.25, 0.25]
try:
tstv = self.tstv.parseString(s).asList()
except ParseException as err:
logger.error(err)
rates = [1.0, tstv[0], 1.0, 1.0, tstv[0], 1.0]
elif model == 'F81':
try:
freq = self.freq.parseString(s).asList()
except ParseException as err:
logger.error(err)
rates = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
elif model == 'F84' or model == 'HKY85' or model == 'TN93':
parser = Group(self.tstv) + Group(self.freq)
try:
tstv, freq = parser.parseString(s).asList()
except ParseException as err:
logger.error(err)
if model == 'TN93':
rates = [1.0, tstv[0], 1.0, 1.0, tstv[1], 1.0]
else:
rates = [1.0, tstv[0], 1.0, 1.0, tstv[0], 1.0]
elif model == 'GTR':
parser = Group(self.freq) + Group(self.rates)
try:
freq, rates = parser.parseString(s).asList()
except ParseException as err:
logger.error(err)
return model, alpha, lnl, freq, rates
示例2: parse_showhdinfo
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_showhdinfo(stdout, stderr):
"""
"""
uuid_prefix = Suppress(Word('UUID:'))
id_uuid = Word(alphanums + '-').setResultsName('uuid')
accessible_prefix = Suppress(Word('Accessible:'))
id_accessible = Word(alphas).setResultsName('accessible')
logical_size_prefix = Suppress(Word('Logical size:'))
id_logical_size = Word(alphanums + ' ').setResultsName('logical_size')
current_size_prefix = Suppress(Word('Current size on disk:'))
id_current_size = Word(alphanums + ' ').setResultsName('current_size')
type_prefix = Suppress(Word('Type:'))
id_type = Word(alphas + ' ()').setResultsName('type')
prefix_storage_format = Suppress(Word('Storage format:'))
id_storage_format = Word(alphas).setResultsName('storage_format')
prefix_format_variant = Suppress(Word('Format variant:'))
id_format_variant = Word(alphanums + ' ').setResultsName('format_variant')
prefix_location = Suppress(Word('Location:'))
id_location = Word(alphanums + ' /.').setResultsName('location')
hd_info = Group(uuid_prefix + id_uuid + EOL + accessible_prefix +
id_accessible + EOL + logical_size_prefix + id_logical_size + EOL +
current_size_prefix + id_current_size + EOL + type_prefix +
id_type + EOL + prefix_storage_format + id_storage_format + EOL +
prefix_format_variant + id_format_variant + EOL + prefix_location +
id_location + EOL)
out = hd_info.parseString(stdout)[0]
return {'uuid': out.uuid, 'accessible': out.accessible,
'logical_size': out.logical_size, 'current_size': out.current_size,
'type': out.type, 'storage_format': out.storage_format,
'format_variant': out.storage_variant, 'location': out.location}
示例3: _read_solution
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def _read_solution(scenario,log,task_to_id,id_to_resource) :
S = scenario
# parse output
from pyparsing import Keyword,Literal,Word,alphas,nums,printables,OneOrMore,ZeroOrMore,dblQuotedString,Group
INT = Word( nums )
int_row = Group( INT + Literal(",").suppress() + \
INT + Literal(",").suppress() + \
INT + Literal(";").suppress() )
plan = Group( Group( ZeroOrMore(int_row) ) )
start_str, end_str = '##START_SOLUTION##', '##END_SOLUTION##'
start_i, end_i = log.index(start_str)+len(start_str), log.index(end_str)
opl_plan = plan.parseString(log[start_i:end_i])
int_plan = opl_plan[0][0]
# get starts and resource assignments
starts = dict()
assign = dict()
for row in int_plan :
task_id = int(row[0])
starts[task_id] = int(row[2])
if task_id not in assign :
assign[task_id] = list()
assign[task_id].append(int(row[1]))
# add to scenario
for T in S.tasks() :
T.start = starts[task_to_id[T]] #second column is start
if T.resources is None :
T.resources = list()
T.resources += [ id_to_resource[j] for j in assign[task_to_id[T]] ]
示例4: parse_connection_str
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_connection_str(connstr):
## Grammar for connection syntax
digits="0123456789"
othervalid="[email protected]"
identifier= Word(alphas+digits+othervalid)
nodename=identifier.setResultsName('nodename')
outputnames = delimitedList( identifier ).setResultsName('outputnames')
inputnames = delimitedList( identifier ).setResultsName('inputnames')
# middle nodes have both inputs and outputs
middlenode= Group( nodename + Suppress('(') + inputnames
+ Optional( "|" + outputnames)
+ Suppress(")") ).setResultsName('middlenode')
# first node has only outputs
headnode = (nodename + Suppress("(") + outputnames
+ Suppress(")")).setResultsName('headnode')
# last node has only inputs
tailnode = (nodename + Suppress("(") + inputnames
+ Suppress(")")).setResultsName('tailnode')
# connect head -> [middle ->] tail
connect= Group( headnode
+ Group(ZeroOrMore(Suppress("->") \
+ middlenode + FollowedBy("->") )).setResultsName('middlenodes')
+ Suppress("->")+tailnode).setResultsName('nodes')
connectlist = Group( connect + ZeroOrMore( Suppress(";")\
+ connect )).setResultsName('connects')
parsed=connectlist.parseString(connstr)
check_numconnections(parsed)
return parsed
示例5: parseReactions
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parseReactions(reaction):
grammar = Group(Word(alphanums) + Suppress('()') + Optional(Suppress('+') + Word(alphanums)
+ Suppress("()"))) + Suppress("->") + Group(Word(alphanums) + Suppress("()") + Optional(Suppress('+')
+ Word(alphanums) + Suppress("()"))) + Suppress(Word(alphanums + "()"))
return grammar.parseString(reaction).asList()
示例6: parseReactions
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parseReactions(reaction):
components = (Word(alphanums + "_") + Optional(Group('~' + Word(alphanums+"_")))
+ Optional(Group('!' + Word(alphanums+'+?'))))
molecule = (Word(alphanums + "_")
+ Optional(Suppress('(') + Group(components) + ZeroOrMore(Suppress(',') + Group(components))
+Suppress(')')))
species = Group(molecule) + ZeroOrMore(Suppress('.') + Group(molecule))
result = species.parseString(reaction).asList()
return result
示例7: read_tgf
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def read_tgf(path):
"""Generates an alias.ArgumentationFramework from a Trivial Graph Format (.tgf) file.
Trivial Graph Format (TGF) is a simple text-based file format for describing graphs. \
It consists of a list of node definitions, which map node IDs to labels, followed by \
a list of edges, which specify node pairs and an optional edge label. \
Node IDs can be arbitrary identifiers, whereas labels for both nodes and edges are plain strings.
Parameters
----------
path : file or string
File, directory or filename to be read.
Returns
-------
framework : alias ArgumentationFramework
Examples
--------
References
----------
http://en.wikipedia.org/wiki/Trivial_Graph_Format
"""
try:
from pyparsing import Word, alphanums, ZeroOrMore, White, Suppress, Group, ParseException, Optional
except ImportError:
raise ImportError("read_tgf requires pyparsing")
if not isinstance(path, str):
return
# Define tgf grammar
s = White(" ")
tag = Word(alphanums)
arg = Word(alphanums)
att = Group(arg + Suppress(s) + arg + Optional(Suppress(s) + tag))
nl = Suppress(White("\n"))
graph = Group(ZeroOrMore(arg + nl)) + Suppress("#") + nl + Group(ZeroOrMore(att + nl) + ZeroOrMore(att))
f = open(path, 'r')
f = f.read()
head, tail = ntpath.split(path)
framework = al.ArgumentationFramework(tail)
try:
parsed = graph.parseString(f)
except ParseException, e:
raise al.ParsingException(e)
示例8: parse_startvm
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_startvm(stdout, stderr):
"""
"""
waiting_prefix = Word('Waiting for VM')
waiting_uuid = UUID_STRING.setResultsName('waiting_uuid')
waiting_postfix = Word('to power on...')
success_prefix = Word('VM')
success_uuid = UUID_STRING.setResultsName('success_uuid')
success_postfix = Word("has been successfully started.")
total = Group(waiting_prefix + DBLQUOTE + waiting_uuid + DBLQUOTE +
waiting_postfix + EOL + success_prefix + DBLQUOTE + success_uuid +
DBLQUOTE + success_postfix)
out = total.parseString(stdout)[0]
return {'uuid': out.success_uuid}
示例9: parse_createvm
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_createvm(stdout, stderr):
"""
"""
single_quote = Suppress(Literal('\''))
name_prefix = Suppress(Word('Virtual machine'))
id_name = Word(alphanums).setResultsName('name')
name_postfix = Suppress(Word('is created and registered.'))
uuid_prefix = Suppress(Word('UUID:'))
id_vm_uuid = Word(srange("[a-zA-Z0-9_\-]")).setResultsName('uuid')
file_prefix = Suppress(Word('Settings file:'))
id_file_path = Word(alphanums + " /.").setResultsName('file_path')
vm_info = Group(name_prefix + single_quote + id_name +
single_quote + name_postfix + EOL + uuid_prefix + id_vm_uuid + EOL +
file_prefix + single_quote + id_file_path + single_quote + EOL)
out = vm_info.parseString(stdout)[0]
return {'name': out.name, 'uuid': out.uuid, 'file_path': out.file_path}
示例10: parse_p4
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_p4(spec):
p4header = p4_header()
p4parser, p4starter = p4_parser()
p4action = p4_action()
p4 = Group(ZeroOrMore(p4header) & ZeroOrMore(p4action) & ZeroOrMore(p4parser) & Optional(p4starter))
parsed = p4.parseString(spec)[0]
grouped = {'headers':[], 'parsers':[], 'actions':[]}
for group in parsed:
if 'header' in group:
grouped['headers'].append(group)
elif 'parser' in group.asList():
grouped['parsers'].append(group[1:])
elif 'action' in group.asList():
grouped['actions'].append(group[1:])
else:
raise Exception("Part of P4 description not categoriased!")
return grouped
示例11: CommandLineParser
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
class CommandLineParser(object):
def __init__(self):
dash = Word("-",max=2)
operator = oneOf(": =")
argValueType1 = quotedString.setParseAction(removeQuotes)
argValueType2 = Regex("[a-zA-Z0-9_\./]+")
positionalArgument = (argValueType1 | argValueType2)
regularArgument = Combine(dash + Word(alphas) + operator + (argValueType1 | argValueType2))
novalueArgument = Combine(dash + Word(alphas))
arguments = ZeroOrMore(positionalArgument | regularArgument | novalueArgument)
self.parser = Group(Word(alphas) + arguments).setResultsName("command")
def parseString(self, querystring):
return self.parser.parseString(querystring)
示例12: parse_config_file
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_config_file(filepath):
"""
This function defines that to parsed the netscalar input file
:param filepath: path of netscalar input configuration
:return: return parsed dict
"""
EOL = LineEnd().suppress()
comment = Suppress("#") + Suppress(restOfLine) + EOL
SOL = LineStart().suppress()
blank_line = SOL + EOL
result = []
hyphen = Literal("-")
not_hyphen_sign = ''.join(c for c in printables if c != '-')
text = Word(not_hyphen_sign, printables)
key = Word('-', printables).setParseAction(
lambda t: t[0].replace('-', '', 1))
val = originalTextFor(Optional(ZeroOrMore(text), default=None))
option = Group(key + val)
multi_word_names = quotedString
q_obj = originalTextFor(Keyword('q{')+SkipTo(Keyword("}")))
command = Group(OneOrMore(q_obj | multi_word_names | text) + ZeroOrMore(option))
command.ignore(comment | blank_line)
with open(filepath) as infile:
line_no = 1
print "Parsing Input Configuration..."
lines = infile.readlines()
total_lines = len(lines)
for line in lines:
try:
tmp = command.parseString(line)
tokens = tmp.asList()
if tokens:
tokens[0].append(['line_no', str(line_no)])
result += tokens
line_no += 1
except Exception as exception:
line_no += 1
LOG.error("Parsing error: " + line)
msg = "Parsing started..."
if line_no <= total_lines:
ns_util.print_progress_bar(line_no, total_lines, msg, prefix='Progress',
suffix='')
return result
示例13: parse_pabl
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
def parse_pabl(self, raw_pabl):
INDENT = lineEnd.suppress() + empty + empty.copy().setParseAction(
self.check_sub_indent)
UNDENT = FollowedBy(empty).setParseAction(self.check_unindent)
UNDENT.setParseAction(self.unindent)
terminator = Literal(';').suppress()
comment = Literal('#') + restOfLine
item_name = Word(alphas, alphanums + '_')
variable = Word(alphas, alphanums + '_.')
variable_as = (variable + 'as' + item_name)
stmt = Forward()
suite = Group(
OneOrMore(empty + stmt.setParseAction(self.check_peer_indent)))
suite.ignore(comment)
item_start = Literal('@item').suppress()
item_end = Literal(':').suppress()
permission_start = Literal('@permissions')
item_decl = (item_start + item_name.setResultsName('item') + item_end)
item_defn = Group(item_decl + INDENT + suite + UNDENT)
permission_decl = (permission_start + Group(
delimitedList(item_name).setResultsName('permissions')) + item_end)
permission_defn = Group(permission_decl + INDENT + suite + UNDENT)
fieldList = delimitedList(
Group(variable_as) | variable
).setResultsName('fields') + terminator
stmt << (item_defn | fieldList | Group(permission_defn))
parseTree = suite.parseString(raw_pabl)
return parseTree
示例14: JSONCommandLineParser
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
class JSONCommandLineParser(object):
def __init__(self):
dash = Word("-",max=2)
operator = oneOf(": =")
argValueType1 = quotedString.setParseAction(removeQuotes)
argValueType2 = Regex("[a-zA-Z0-9_\./]+")
positionalArgument = (argValueType1 | argValueType2)
regularArgument = Combine(dash + Word(alphas) + operator + (argValueType1 | argValueType2))
novalueArgument = Combine(dash + Word(alphas))
arguments = ZeroOrMore(positionalArgument | regularArgument | novalueArgument)
self.parser = Group(Word(alphas) + arguments).setResultsName("command") + SkipTo(Word("{[")).setParseAction(self.jsonData)
def jsonData(self, commandtext, location, tokens):
startindex = location + len("".join(tokens))
return commandtext[startindex:]
def parseString(self, querystring):
result = self.parser.parseString(querystring)
return {"command":result.command,
"filedata":result[1]}
示例15: SExpressionParser
# 需要导入模块: from pyparsing import Group [as 别名]
# 或者: from pyparsing.Group import parseString [as 别名]
class SExpressionParser(object):
def __init__(self):
self.lpar = Literal('(')
self.rpar = Literal(')')
self.word_chars = ''.join(c for c in printables if c not in ('()'))
self.word = Word(self.word_chars) | quotedString
self.atom = self.word
self.expression = Forward()
self.composite_expression = (
Suppress(self.lpar) +
ZeroOrMore(self.expression) +
Suppress(self.rpar))('composite_expression')
self.composite_expression.addParseAction(
self._composite_expression_to_tuple)
self.expression << (self.atom | self.composite_expression)
self.expressions = Group(ZeroOrMore(self.expression))('expressions')
self.expressions.addParseAction(self._expressions_to_tuple)
def parse_expression(self, instring):
return self.expression.parseString(instring, parseAll=True)[0]
def parse_expressions(self, instring):
return self.expressions.parseString(instring, parseAll=True)[0]
@staticmethod
def _composite_expression_to_tuple(toks):
return SExpression(toks.composite_expression)
@staticmethod
def _expressions_to_tuple(toks):
return SExpressionList(toks.expressions)