本文整理汇总了Python中pyparsing.Word.parseString方法的典型用法代码示例。如果您正苦于以下问题:Python Word.parseString方法的具体用法?Python Word.parseString怎么用?Python Word.parseString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyparsing.Word
的用法示例。
在下文中一共展示了Word.parseString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def __init__(self, params):
self.name = ""
self.type = None
self.default_value = None
self.range = None
if isinstance(params, list):
self.name = params[0]
for attr in params[1:]:
if attr[0] == 'default':
self.default_value = attr[1]
elif attr[0] == 'type':
assert attr[1] == 'string' or attr[1] == 'integer'
self.type = attr[1]
elif attr[0] == 'range':
self.range = [attr[1], attr[2]]
if int(self.range[0]) >= int(self.range[1]):
raise ValueError('Invalid range')
if not self.default_value is None:
try:
# consistenza di tipo sui valori dello slot corrente
parser = Word(alphas) if self.type == 'string' else Word(nums)
parser.parseString(self.default_value)
# se slot corrente ha un range definito
if not self.range is None:
spec_range = '{0} >= {1} and {0} <= {2}'.format(self.default_value, self.range[0], self.range[1])
if not eval(spec_range):
raise ValueError('Default value doesn\'t satisfy range constraints')
except (ParseException, SyntaxError):
raise ValueError('Incorrect default value for slot')
else:
self.name = params
示例2: check_slot_value
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def check_slot_value(self, slot_value):
try:
if not self.type is None:
parser = Word(alphas) if self.type == 'string' else Word(nums)
parser.parseString(slot_value)
if not self.range is None and self.type != 'string':
spec_range = '{0} >= {1} and {0} <= {2}'.format(slot_value, self.range[0], self.range[1])
if not eval(spec_range):
return False
return True
except (ParseException, SyntaxError):
return False
示例3: set_param
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def set_param(self,line):
# define grammar
a = line.find("]")
b = line.find("=")
if(a>0 and b>0 and (b-a)==1):
return
else:
modele = Word( alphas ) + "[" + Word(nums) + "]" + Word(objectPath) + "=" + Word( divers )
try:
pd = modele.parseString( line )
except ParseException as pe:
pass
else:
obj = pd[0]
key = pd[4]
value = pd[6][:len(pd[6])-1]
nb = int(pd[2])
if(key[0]=="."):
key = key[1:] #expect ".keyword"
if(key.find(".")<0): #a single keyword
if(key in ("ref")):
setattr(self,key,set_str(value))
#print("-> ocd[{id}].{key}={value}".format(id=self.id,key=key,value=value))
elif(key in ("start","resolution")):
setattr(self,key,float(value))
#print("-> ocd[{id}].{key}={value}".format(id=self.id,key=key,value=value))
elif(key in ("bp","sigma")):
setattr(self,key,np.array([float(x) for x in commaSeparatedList.parseString(set_str(value))]))
示例4: load_variables
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def load_variables(filename):
"""Load random variables definitions from file (in C45 format but with class at the end).
File must contain information in format 'Variable Name: Values.' as in the example below:
A: true,false.
B: 0,1,2.
C: c1,c2,c3,c4.
D: one.
"""
from DataStructures.randomvariables import RandomVariable
RV = []
# variable = Word(caps + lowers + digits).setResultsName("name") + ": " + OneOrMore(Group(Word(caps + lowers + digits) + Optional("." + Word(caps + lowers + digits))) + Suppress(Optional(","))).setResultsName("domain") + "."
variable = Word(caps + lowers + digits).setResultsName("name") + ": " + OneOrMore(Word(caps + lowers + digits + ".") + Optional(Suppress(","))).setResultsName("domain")
for line in file(filename):
if not line[0] == '#':
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)
return RV
示例5: open
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def open(self, id):
self.id = id
item = 'BODY'
typ, data = self.imap.fetch(id, '(' + item + ')')
assert typ == 'OK'
inline_parse = Forward()
inline_parse << Suppress("(") + Group(OneOrMore(Or([Keyword("NIL"), QuotedString('"'), Word(nums), inline_parse ]))) + Suppress(")")
parse = Word(nums) + Suppress("(") + Keyword(item) + Suppress("(") + Group(OneOrMore(inline_parse)) + ZeroOrMore(Or([Keyword("NIL"), QuotedString('"'), Word(nums)])) + Suppress(")") + Suppress(")")
p = parse.parseString(data[0])
#print data[0]
#print p
#print
self.attachment = []
for i in p[2]:
#while 'NIL' in i:
# i.remove('NIL')
a = {
'type' : '/'.join(i[0:2]).lower(),
i[2][0].lower() : i[2][1],
}
self.attachment.append(a)
示例6: parse
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def parse(operator, string, digits=None):
"""Parse a valid interval from strings like '1800-1900' or '12'. If operator is one of
('<=', '>=', '>', '<'), only a single number will be parsed and an open interval will be constructed.
If the optional paramater *digits* is specified, only numbers having exactly this number of digits
will be considered.
"""
string = string.strip()
if digits is not None:
number = Word(pyparsing.nums, exact=digits)
else: number = Word(pyparsing.nums)
try:
if operator not in ('<=', '>=', '>', '<'):
# the ^ means xor. | does not work together with parseAll=True (bug in pyparsing?)
parser = number ^ (number + Suppress('-') + number)
result = parser.parseString(string, parseAll=True).asList()
result = [int(r) for r in result]
if len(result) == 1:
return Interval(result[0], result[0])
else: return Interval(result[0], result[1])
else:
result = number.parseString(string)
date = int(result[0])
if operator == '>=':
return Interval(date, None)
elif operator == '<=':
return Interval(None, date)
elif operator == '>':
return Interval(date+1, None)
elif operator == '<':
return Interval(None, date-1)
else: assert False
except pyparsing.ParseException:
return None
示例7: read_stats
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def read_stats(result_dir, stats_file_name):
stat_rule = Word(printables) + Word('nan.%' + nums) + Optional(restOfLine)
stats = []
try:
with open(path.join(result_dir, stats_file_name)) as stats_file:
i = 0
for stat_line in stats_file:
if len(stats) <= i:
stats.append(collections.OrderedDict())
try:
stat = stat_rule.parseString(stat_line)
key = stat[0]
value = stat[1]
stats[i][key] = value
except ParseException as e:
# print(e)
pass
if 'End Simulation Statistics' in stat_line:
i += 1
except Exception as e:
print(e)
return None
else:
return stats
示例8: ValidateName
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def ValidateName(self,Nn,T):
from pyparsing import Word,alphas,nums,ParseException
G=Word(alphas+"_", alphas+nums+"_")
G.setDebug(False)
try:
ps=G.parseString(Nn, parseAll=True)
Nn=ps[0]
except ParseException,PE:
self.PRINT(PE.line)
self.PRINT(" "*(PE.column-1) + "^")
self.ERROR(64,T,PE)
示例9: pars_data
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def pars_data(): #Парсинг файла с данными
f = open("test.txt" ,'r')
all_lines = f.readlines()
last_line = []
last_line.append(all_lines[-1])
for item in last_line:
item += item
temperatura = (Word(nums + '+.') | Word(nums + '-.'))
comma = (Literal(",") | Literal(";")).suppress()
tem = (temperatura + comma)*5
full_name_temperatura = Word(nums + '.').suppress() + Word(nums + ':').suppress() + tem # парсинг температуры
vremenno_temp= full_name_temperatura.parseString(item) # парсинг температуры
full_name_date = Word(nums + '.') # парсинг даты
vremenno_date = full_name_date.parseString(item) # парсинг даты
data_date = str(vremenno_date) # парсинг даты
data_temperatura = [] # парсинг температуры
for item in vremenno_temp: # парсинг температуры
item = float(item) # парсинг температуры
data_temperatura.append(item) # парсинг температуры
f.close
return data_temperatura
示例10: load_c45_header
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word 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
示例11: load_graph
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def load_graph(filename):
"""Load a graph from file into an adjacency map.
input: input filename
output: graph as adjancency map G
File must contain graph as an adjancency list such as
A: B,C
B: C
C: .
Ending vertices should also be represented explicitly as linking to a dot
"""
G = {}
node = Word(caps + lowers + digits).setResultsName("node") + ": " + OneOrMore(Word(caps + lowers + digits + empty) + Suppress(Optional(","))).setResultsName("edges")
for line in file(filename):
graph = node.parseString(line)
G[graph.node] = graph.edges
return G
示例12: parseTypes
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def parseTypes(path):
msgs = set()
types = {}
for line in lineGen(path):
number = Word(nums)
word = Word(alphanums + "-_")
wordList = Forward()
wordList = word + ZeroOrMore(',' + word)
par = (Literal('NetworkPartition').setResultsName('type') +\
'(' + Literal('Set') + '(' +\
wordList.setResultsName('p1') + ')' + ',' +\
Literal('Set') + '(' +\
wordList.setResultsName('p2') + ')' + \
')')
subType = (word + Optional(nestedExpr('(', ')'))).setResultsName('msg')
msg = (Literal('MsgEvent').setResultsName('type') +\
'(' + word.setResultsName('src') + ',' +\
word.setResultsName('dst') + ',' +\
subType + ')')
event = Word( nums ) +\
Literal('Unique') + "(" + (msg | par) + ',' +\
number.setResultsName('uid') + ')'
result = event.parseString(line)
key = result.uid
if result.type == 'MsgEvent':
msg = list2tuple( result.msg.asList() )
value = (result.type, result.src, result.dst, msg)
msgs.add(msg)
elif result.type == 'NetworkPartition':
value = (result.type, result.p1, result.p2)
types[key] = value
return types
示例13: parse_OxCal_data
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def parse_OxCal_data(oxcal_js_file):
myOCD = {}
myCalib = {}
# Ouverture d'un fichier en *lecture*:
fichier = open(oxcal_js_file, 'r')
for ligne in fichier:
modele = Word( alphas ) + '[' + Word(nums) + ']' + Word( printables )
try:
parsed_data = modele.parseString( ligne )
except ParseException, pe:
pass
else:
flg = parsed_data[0]
nb = int(parsed_data[2])
if(flg==u"ocd"):
if(not myOCD.has_key(nb)):
myOCD[nb] = OxCalData(nb)
myOCD[nb].set_param(ligne)
elif(flg==u"calib"):
if(not myCalib.has_key(nb)):
myCalib[nb] = Calibration(nb)
myCalib[nb].set_param(ligne)
示例14: xrange
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
# vim:fileencoding=utf-8
#
# greetingInGreek.py
#
# Demonstration of the parsing module, on the prototypical "Hello, World!" example
#
from pyparsing import Word
# define grammar
alphas = u''.join(unichr(x) for x in xrange(0x386, 0x3ce))
greet = Word(alphas) + u',' + Word(alphas) + u'!'
# input string
hello = "Καλημέρα, κόσμε!".decode('utf-8')
# parse input string
print greet.parseString( hello )
示例15: file_len
# 需要导入模块: from pyparsing import Word [as 别名]
# 或者: from pyparsing.Word import parseString [as 别名]
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
symbols="-'"
txt=open("dale_chall.txt")
n_lines=file_len("dale_chall.txt")
n_count=1
word_list=[]
print n_lines
for i in range(n_lines):
line=txt.readline()
print 'line', line
parse1=Word(alphas)
parsed=parse1.parseString(line)
print 'parsing', parsed[0],parsed
word_list.append(parsed[0])
print len(word_list), word_list
pickle.dump( word_list, open('dale_chall.p', "wb" ) )