本文整理汇总了Python中pyparsing.OneOrMore.parseString方法的典型用法代码示例。如果您正苦于以下问题:Python OneOrMore.parseString方法的具体用法?Python OneOrMore.parseString怎么用?Python OneOrMore.parseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.OneOrMore
的用法示例。
在下文中一共展示了OneOrMore.parseString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pyparsing_parse
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def pyparsing_parse(text):
WHITESPACE = re.compile(r"\s+")
books = {}
key_values = {}
def normalize(tokens):
return WHITESPACE.sub(" ", tokens[0])
def add_key_value(tokens):
key_values[tokens.key] = tokens.value
def add_book(tokens):
books[tokens.identifier] = key_values.copy()
key_values.clear()
left_brace, right_brace, comma, equals = map(Suppress, "{},=")
start = Suppress("@Book") + left_brace
identifier = Regex(r"[a-zA-Z][^,\s]*")("identifier") + comma
key = Word(alphas, alphanums)("key")
value = (Word(nums).setParseAction(lambda t: int(t[0])) |
QuotedString('"', multiline=True).setParseAction(normalize)
)("value")
key_value = (key + equals + value).setParseAction(add_key_value)
end = right_brace
bibtex = (start + identifier + delimitedList(key_value) + end
).setParseAction(add_book)
parser = OneOrMore(bibtex)
try:
parser.parseString(text)
except ParseException as err:
print("parse error: {0}".format(err))
return books
示例2: parseEqun
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def parseEqun(equation):
cForm = Word(ascii_uppercase, ascii_uppercase + ascii_lowercase + digits)
equnExpr = Group(ZeroOrMore(cForm + Suppress('+')) + cForm)
lhs = equnExpr.setResultsName('lhs')
rhs = equnExpr.setResultsName('rhs')
chemicalEqun = lhs + "->" + rhs
parsedEqun = chemicalEqun.parseString(equation)
LHS = parsedEqun['lhs'].asList()
RHS = parsedEqun['rhs'].asList()
lhsDict = {}
rhsDict = {}
element = Word(ascii_uppercase, ascii_lowercase)
integer = Word(digits).setParseAction(lambda x: int(x[0]))
elementRef = Group(element + Optional(integer, default=1))
chemicalFormula = OneOrMore(elementRef)
for chemical in LHS:
lhsDict[chemical] = Counter()
for element, count in chemicalFormula.parseString(chemical):
lhsDict[chemical][element] += count
for chemical in RHS:
rhsDict[chemical] = Counter()
for element, count in chemicalFormula.parseString(chemical):
rhsDict[chemical][element] += count
return lhsDict, rhsDict
示例3: main
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def main(index,line):
# Do something with this data.
if line is not None:
try:
operator = Regex(r'(?<![\+\-\^\*/%])[\+\-]|[\^\*/%!]')
function = Regex(r'[a-zA-Z_][a-zA-Z0-9_]*(?=([ \t]+)?\()')
variable = Regex(r'[+-]?[a-zA-Z_][a-zA-Z0-9_]*(?!([ \t]+)?\()')
number = Regex(r'[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?')
lbrace = Word('(')
rbrace = Word(')')
assign = Literal(':=')
linebreak = Word('\n')
skip = Word(' \t')
lexOnly = operator | function | variable | number | lbrace \
| rbrace | assign | linebreak | skip
lexAllOnly = OneOrMore(lexOnly)
print lexAllOnly.parseString(line)
print '\n------------------------------\n'
except ParseException, err:
print err.line
print " "*(err.column-1) + "^"
print "Error en la linea, {index}, columna: {e.col} elemento no identificado".format(e=err,index=index)
print '\n------------------------------\n'
示例4: SGF
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
class SGF(object):
def __init__(self, filename):
# BNF
start = Literal(";")
text = QuotedString(quoteChar="[",
escChar="\\",
multiline=True,
unquoteResults=True,
endQuoteChar="]")
prop_id = Word(srange("[A-Za-z]"), min=1, max=10)
prop = prop_id + Group(OneOrMore(text))
node = ZeroOrMore(start) + OneOrMore(prop)
sequence = OneOrMore(node)
branch = Forward()
branch << "(" + sequence + ZeroOrMore(branch) + ")"
self.game = OneOrMore(branch)
self.sgf_content = filename
self.moves = None
self.__parse()
self.current = 0
def next_token(self):
tok = self.moves[self.current]
self.current += 1
if _debug_:
print "SGF: ", tok
return tok
def __parse(self):
self.moves = self.game.parseString(self.sgf_content)
def show(self):
print "All moves in %s" % self.sgf_content
pprint(self.moves)
示例5: parse_string
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [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 quotedString, restOfLine, Keyword, nestedExpr, OneOrMore, Word, Literal, removeQuotes
gr_eq = Literal('=')
gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
gr_opt_quoted_string = gr_stripped_string | restOfLine
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
gr_line = np((NAME,), action=lambda x: self._set_name(x[2]))
for key in self.NULL_KEYS:
if key == id: continue
gr_line = gr_line | np((key,), action=self._parse_setter(key))
gr_res = OneOrMore(gr_line)
result = gr_res.parseString(string, parseAll=True)
return 'Console: ' + self[NAME]
示例6: parse_string
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [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!
FTR: this is hideous.
'''
from pyparsing import Suppress, Regex, quotedString, restOfLine, Keyword, nestedExpr, Group, OneOrMore, Word, Literal, alphanums, removeQuotes, replaceWith, nums, printables
gr_eq = Literal('=')
gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
gr_opt_quoted_string = gr_stripped_string | restOfLine
gr_number = Word(nums)
gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))
def _handle_ip(*x):
a,b,c = x[2]
return ' %s = { %s }' % (a,c[0])
def _handle_diraddr(*x):
a,b,c = x[2]
self._set(DIRADDRESSES, ' %s' % '\n '.join(c))
return
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
gr_name = np((NAME,), action=lambda x: self._set_name(x[2]))
gr_address = np((ADDRESS,), action=self._parse_setter(ADDRESS))
gr_fd_conn = np(PList('fd connect timeout'), gr_number, self._parse_setter(FD_CONNECT_TIMEOUT, True))
gr_heart = np(PList('heartbeat interval'), gr_number, self._parse_setter(HEARTBEATINTERVAL, True))
gr_max_con = np(PList('maximum console connections'),
gr_number, self._parse_setter(MAXIMUMCONSOLECONNECTIONS, True))
gr_max_jobs = np(PList('maximum concurrent jobs'), gr_number, action=self._parse_setter(MAXIMUMCONCURRENTJOBS, True))
gr_pass = np((PASSWORD,), action=self._parse_setter(PASSWORD))
gr_pid = np(PList('pid directory'), action=self._parse_setter(PIDDIRECTORY))
gr_query = np(PList('query file'), action=self._parse_setter(QUERYFILE))
gr_scripts = np(PList('scripts directory'), action=self._parse_setter(SCRIPTS_DIRECTORY))
gr_sd_conn = np(PList('sd connect timeout'), gr_number, self._parse_setter(SD_CONNECT_TIMEOUT, True))
gr_source = np(PList('source address'), action=self._parse_setter(SOURCEADDRESS))
gr_stats = np(PList('statistics retention'), action=self._parse_setter(STATISTICS_RETENTION))
gr_verid = np((VERID,), action=self._parse_setter(VERID))
gr_messages = np((MESSAGES,), action=lambda x:self._parse_setter(MESSAGE_ID, dereference=True))
gr_work_dir = np(PList('working directory'), action=self._parse_setter(WORKINGDIRECTORY))
gr_port = np(PList('dir port'), gr_number, self._parse_setter(PORT, True))
gr_monitor = np((MONITOR,), gr_yn, action=self._parse_setter(MONITOR))
# This is a complicated one
da_addr = np(('Addr','Port'), Word(printables), lambda x,y,z: ' '.join(z))
da_ip = np(('IPv4','IPv6','IP'), nestedExpr('{','}', OneOrMore(da_addr).setParseAction(lambda x,y,z: ' ; '.join(z)))).setParseAction(_handle_ip)
da_addresses = np(PList('dir addresses'), nestedExpr('{','}', OneOrMore(da_ip)), _handle_diraddr)
gr_res = OneOrMore(gr_name | gr_address | gr_fd_conn | gr_heart | gr_max_con | gr_max_jobs | gr_pass | gr_pid | gr_query | gr_scripts | gr_sd_conn | gr_source | gr_stats | gr_verid | gr_messages | gr_work_dir | gr_port | gr_monitor | da_addresses)
result = gr_res.parseString(string, parseAll=True)
return 'Director: ' + self[NAME]
示例7: parse_string
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [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, nums
gr_eq = Literal('=')
gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
gr_opt_quoted_string = gr_stripped_string | restOfLine
gr_number = Word(nums)
gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))
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
gr_line = np((NAME,), action=lambda x: self._set_name(x[2]))
gr_line = gr_line | np(PList('sd port'), gr_number, action=self._parse_setter(SDPORT))
gr_line = gr_line | np((ADDRESS,), action=self._parse_setter(ADDRESS))
gr_line = gr_line | np((PASSWORD,), action=self._parse_setter(PASSWORD))
gr_line = gr_line | np((DEVICE,), action=self._parse_setter(DEVICE))
gr_line = gr_line | np(PList('media type'), action=self._parse_setter(MEDIATYPE))
gr_line = gr_line | np(PList('auto changer'), gr_yn, action=self._parse_setter(AUTOCHANGER))
gr_line = gr_line | np(PList('maximum concurrent jobs'), gr_number, action=self._parse_setter(MAXIMUMCONCURRENTJOBS))
gr_line = gr_line | np(PList('allow compression'), gr_yn, action=self._parse_setter(ALLOWCOMPRESSION))
gr_line = gr_line | np(PList('heartbeat interval'), action=self._parse_setter(HEARTBEATINTERVAL))
gr_res = OneOrMore(gr_line)
result = gr_res.parseString(string, parseAll=True)
return 'Storage: ' + self[NAME]
示例8: order_cluster_by_load
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def order_cluster_by_load(self, cluster_list):
# Sample salt output
# {'dlceph01.drwg.local': '0.27 0.16 0.15 1/1200 26234'}
# define grammar
point = Literal('.')
number = Word(nums)
floatnumber = Combine( number + point + number)
float_list = OneOrMore(floatnumber)
results = self.salt_client.cmd(','.join(cluster_list), 'cmd.run', ['cat /proc/loadavg'], expr_form='list')
load_list = []
self.logger.debug("Salt load return: {load}".format(load=results))
for host in results:
host_load = results[host]
match = float_list.parseString(host_load)
if match:
one_min = match[0]
five_min = match[1]
fifteen_min = match[2]
self.logger.debug("Adding Load({host}, {one_min}, {five_min}, {fifteen_min}".format(
host=host, one_min=one_min, five_min=five_min, fifteen_min=fifteen_min))
load_list.append(Load(host, one_min, five_min, fifteen_min))
else:
self.logger.error("Could not parse host load output")
# Sort the list by fifteen min load
load_list = sorted(load_list, key=lambda x: x.fifteen_min_load)
for load in load_list:
self.logger.debug("Sorted load list: " + str(load))
return load_list
示例9: read_apx
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def read_apx(path):
"""Generates an alias.ArgumentationFramework from an Aspartix (.apx) file.
Parameters
----------
path : file or string
File, directory or filename to be read.
Returns
-------
framework : alias ArgumentationFramework
Examples
--------
References
----------
http://www.dbai.tuwien.ac.at/research/project/argumentation/systempage/docu.htm
"""
try:
from pyparsing import Word, Literal, nums, alphas, alphanums, Keyword, Group, OneOrMore, Suppress
except ImportError:
raise ImportError("read_apx requires pyparsing")
if not isinstance(path, str):
return
# Define apx grammar
LPAR,RPAR,DOT,COMMA = map(Suppress,"().,")
arg,attack,pref,val,valpref,support = map(Keyword,
"arg att pref val valpref support".split())
ID = Word(alphas, alphanums)
id_pair = Group(ID + COMMA + ID)
integer = Word(nums)
int_pair = Group(integer + COMMA + integer)
arg_cmd = (arg + LPAR + ID("arg*") + RPAR)
attack_cmd = (attack + LPAR + id_pair("att*") + RPAR)
pref_cmd = (pref + LPAR + id_pair("pref*") + RPAR)
val_cmd = (val + LPAR + Group(ID + COMMA + integer)("val*") + RPAR)
valpref_cmd = (valpref + LPAR + int_pair("valpref*") + RPAR)
support_cmd = (support + LPAR + id_pair("support*") + RPAR)
apx = OneOrMore((arg_cmd | attack_cmd | pref_cmd | val_cmd | valpref_cmd | support_cmd) + DOT)
f = open(path, 'r')
f = f.read()
head, tail = ntpath.split(path)
framework = al.ArgumentationFramework(tail)
try:
parsed = apx.parseString(f)
except ParseException, e:
raise al.ParsingException(e)
示例10: analyzeVerse
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def analyzeVerse(instr):
swp = swap_agaram(unicode(instr))
parse_syntax = OneOrMore(adi).leaveWhitespace()
try:
result = parse_syntax.parseString(swp, parseAll=True)
return generateXML(result)
except Exception,e:
return None
示例11: parse_string
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [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 quotedString, restOfLine, Keyword, nestedExpr, OneOrMore, Word, Literal, removeQuotes, nums, replaceWith, printables
gr_eq = Literal('=')
gr_stripped_string = quotedString.copy().setParseAction( removeQuotes )
gr_opt_quoted_string = gr_stripped_string | restOfLine
gr_number = Word(nums)
gr_yn = Keyword('yes', caseless=True).setParseAction(replaceWith('1')) | Keyword('no', caseless=True).setParseAction(replaceWith('0'))
def _handle_ip(*x):
a,b,c = x[2]
return ' %s = { %s }' % (a,c[0])
def _handle_fdaddr(*x):
a,b,c = x[2]
self._set(FDADDRESSES, ' %s' % '\n '.join(c))
return
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
gr_line = np((NAME,), action=lambda x: self._set_name(x[2]))
gr_line = gr_line | np((ADDRESS,), action=self._parse_setter(ADDRESS))
gr_line = gr_line | np((CATALOG,), action=self._parse_setter(CATALOG_ID, dereference=True))
gr_line = gr_line | np((PASSWORD,), action=self._parse_setter(PASSWORD))
gr_line = gr_line | np(PList('file retention'), action=self._parse_setter(FILERETENTION))
gr_line = gr_line | np(PList('job retention'), action=self._parse_setter(JOBRETENTION))
gr_line = gr_line | np((PRIORITY,), gr_number, action=self._parse_setter(PRIORITY))
gr_line = gr_line | np(PList('working directory'), action=self._parse_setter(WORKINGDIRECTORY))
gr_line = gr_line | np(PList('pid directory'), action=self._parse_setter(PIDDIRECTORY))
gr_line = gr_line | np(PList('heart beat interval'), action=self._parse_setter(HEARTBEATINTERVAL))
gr_line = gr_line | np(PList('fd address'), action=self._parse_setter(FDADDRESS))
gr_line = gr_line | np(PList('fd source address'), action=self._parse_setter(FDSOURCEADDRESS))
gr_line = gr_line | np(PList('pki key pair'), action=self._parse_setter(PKIKEYPAIR))
gr_line = gr_line | np(PList('pki master key'), action=self._parse_setter(PKIMASTERKEY))
gr_line = gr_line | np(PList('fd port'), gr_number, action=self._parse_setter(FDPORT))
gr_line = gr_line | np(PList('auto prune'), gr_yn, action=self._parse_setter(AUTOPRUNE))
gr_line = gr_line | np(PList('maximum concurrent jobs'), gr_number, action=self._parse_setter(FDPORT))
gr_line = gr_line | np(PList('pki encryption'), gr_yn, action=self._parse_setter(PKIENCRYPTION))
gr_line = gr_line | np(PList('pki signatures'), gr_yn, action=self._parse_setter(PKISIGNATURES))
# This is a complicated one
da_addr = np(('Addr','Port'), Word(printables), lambda x,y,z: ' '.join(z))
da_ip = np(('IPv4','IPv6','IP'), nestedExpr('{','}', OneOrMore(da_addr).setParseAction(lambda x,y,z: ' ; '.join(z)))).setParseAction(_handle_ip)
da_addresses = np(('fd addresses', FDADDRESSES), nestedExpr('{','}', OneOrMore(da_ip)), _handle_fdaddr)
gr_res = OneOrMore(gr_line|da_addresses)
result = gr_res.parseString(string, parseAll=True)
return 'Client: ' + self[NAME]
示例12: split_chemical_formula
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def split_chemical_formula(formula):
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def replace_things(stringg, listt, replacement):
for x in listt:
stringg = stringg.replace(x, replacement)
return stringg
bad_chars = ["(", ")", "-", "."]
formula = replace_things(formula, bad_chars, "|")
if is_number(formula):
return [["", 0]]
if len(formula) == 0:
return [["", 0]]
# define some strings to use later, when describing valid lists
# of characters for chemical symbols and numbers
caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowers = caps.lower()
digits = "0123456789"
# Version 1
# Version 2 - Auto-convert integers, and add results names
def convertIntegers(tokens):
return int(tokens[0])
element = Word(caps, lowers)
integer = Word(digits).setParseAction(convertIntegers)
elementRef = Group(element("symbol") + Optional(integer, default=1)("qty"))
# pre-1.4.7, use this:
# elementRef = Group( element.setResultsName("symbol") + Optional( integer, default=1 ).setResultsName("qty") )
chemicalFormula = OneOrMore(elementRef)
# Version 3 - Compute partial molecular weight per element, simplifying
# summing
# No need to redefine grammar, just define parse action function, and
# attach to elementRef
def computeElementWeight(tokens):
element = tokens[0]
element["weight"] = atomicWeight[element.symbol] * element.qty
elementRef.setParseAction(computeElementWeight)
formulaData = chemicalFormula.parseString(formula)
mw = sum([element.weight for element in formulaData])
return formulaData
示例13: parse_mapdata
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def parse_mapdata(path_to_mapdata):
"""Parse mapdata file into a dictionary that has three values:
num1 (a magic number), num2 (a magic number) and regions which
itself is a dictionary that contains region numbers as keys and
the files as a list.
"""
with open(path_to_mapdata, 'r') as f:
mapdata = f.read()
mapdata_pattern = re.compile("(\d{8})\s*(\d{8})\s*(.*)", re.DOTALL)
num1, num2, data = mapdata_pattern.findall(mapdata)[0]
match = re.search(mapdata_pattern, mapdata)
if not match:
print("An error occured.")
print("The file '%s' was not well-formed." % path_to_mapdata)
sys.exit()
num1, num2, data = match.groups()
logging.debug("num1: %s" % num1)
logging.debug("num2: %s" % num2)
logging.debug("data: %s" % data)
parsed_map_data = {'num1': num1, 'num2': num2, 'regions': {}}
def regionParsing(x):
parsed_map_data['regions'][int(x[0])] = x[1:]
def named(name, rule):
return rule.setResultsName(name).setName(name)
regionnum = named("region-number", Word(nums, exact=2))
filename = named("filename", Word(alphanums + "/."))
tmp = Word("{").suppress() + OneOrMore(filename) + Word("}").suppress()
regiondata = named("region-data", tmp)
region = named("region", (regionnum + regiondata))
region.setParseAction(regionParsing)
map_grammar = OneOrMore(region)
data = data.strip() # a strange character at the end
map_grammar.parseString(data)
return parsed_map_data
示例14: translate
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def translate(self, text, filename):
self.source = text
self.super = None
self.inheritance = 0
self.declaration_lines = ['inheritance = 0']
self.block_lines = []
self.body_lines = ['def body():']
self.target_lines = self.body_lines
self.indent = 1
template_close = Literal('%>')
white = White()
attribute = Word(alphanums + '_') + Literal('=') + QuotedString('"') + Optional(white)
directive = "<%@" + Optional(white) + Word(alphanums + '_') + white + ZeroOrMore(attribute) + template_close
declaration = "<%!" + SkipTo(template_close) + template_close
expression = "<%=" + SkipTo(template_close) + template_close
scriptlet = '<%' + SkipTo(template_close) + template_close
template_text = directive | declaration | expression | scriptlet
plain_text = Regex(r'((?!<%).|\s)+', re.MULTILINE)
body = template_text | plain_text
lit = OneOrMore(body)
directive.setParseAction(self.compile_directive)
declaration.setParseAction(self.compile_declaration)
expression.setParseAction(self.compile_expression)
scriptlet.setParseAction(self.compile_scriptlet)
plain_text.setParseAction(self.compile_plain_text)
lit.leaveWhitespace()
lit.parseString(self.source)
translated = '\n' + '\n'.join(self.declaration_lines + ['\n'] + self.block_lines + ['\n'] + self.body_lines)
if self.super:
translated = self.super.module_source + translated
return translated
示例15: load_c45_header
# 需要导入模块: from pyparsing import OneOrMore [as 别名]
# 或者: from pyparsing.OneOrMore import parseString [as 别名]
def load_c45_header(filename):
"""Load random variables definitions from file (in C45 format).
File must contain information in format 'Variable Name: Values.' as in the example below:
0,1.
A: true,false.
B: 0,1,2.
C: c1,c2,c3,c4.
D: one.
The first line is related to the class object (expressed in last position at the output header)
"""
from DataStructures.randomvariables import RandomVariable
RV = []
cvariable = OneOrMore(Word(caps + lowers + digits + ".") + Optional(Suppress(","))).setResultsName("domain")
variable = Word(caps + lowers + digits).setResultsName("name") + ": " + OneOrMore(Word(caps + lowers + digits + ".") + Optional(Suppress(","))).setResultsName("domain")
class_variable = None
for line in file(filename):
if not line[0] == '#' and len(line) > 1:
if class_variable is None:
dataline = line[0:(len(line)-2)]
#print dataline
rv = cvariable.parseString(dataline)
domain = []
for value in rv.domain:
#print value,
value = ''.join(value)
if value.isdigit():
#print 'lv#', value
domain.append(int(value))
else:
domain.append(value)
#print
class_variable = RandomVariable('class',domain)
else:
dataline = line[0:(len(line)-2)]
#print dataline
rv = variable.parseString(dataline)
#print rv.name
domain = []
for value in rv.domain:
#print value,
value = ''.join(value)
if value.isdigit():
#print 'lv#', value
domain.append(int(value))
else:
domain.append(value)
#print
var = RandomVariable(rv.name,domain)
RV.append(var)
RV.append(class_variable)
return RV