def lex(parsedScript):
lexedScript = parsedScript
functions = []
index = 0
for structure in parsedScript:
if structure[0] == 'use':
proto = ''
pkg = ''
if structure[1].startswith('.'):
proto = structure[1][1:]
else:
proto = '/' + structure[1]
for char in proto:
if char == '.':
pkg += '/'
elif char == '/':
print('Error: Invalid Syntax.')
sys.exit(1)
else:
pkg += char
lex(parser.parse(open(pkg + '.essl', 'r+').read()))
elif structure[0][0] == 'subroutine':
functions.append(classes.Variable(structure[0][1], structure[1:]))
lexedScript[index].remove(structure[0])
index += 1
return functions
python类parse()的实例源码
def __init__(self, content=None, base_path=None, base_uri=None, strict=False):
if content is not None:
self.data = parse(content, strict)
else:
self.data = {}
self._base_uri = base_uri
if self._base_uri:
if not self._base_uri.endswith('/'):
self._base_uri += '/'
self._initialize_attributes()
self.base_path = base_path
def do_GET(self):
print("GET-Request from " + str(self.client_address))
try:
self.send_response(200) # http-code: 200 -> OK
self.send_header("Content-type", self.getMimeType())
self.end_headers()
if((self.getMimeType() != None) and (self.getMimeType().find("text") != -1)): # text file
contentBytes = self.getContent()
get = ""
# if get != "":
# content = parser.parse(contentBytes.decode("utf-8"), self.getPath(), GET=get)
#else:
content = parser.parse(contentBytes.decode("utf-8"), self.getPath())
self.wfile.write(bytes(content, "utf-8"))
else: # binary file, for example: jpg, png, pdf etc..
self.wfile.write(self.getContent())
except FileNotFoundError as fnfe:
print("File not found: " + str(fnfe))
except IOError:
self.send_error(404, "File not found: " + self.path)
def test_parse_known_values_clean(self):
"""parse should give known result with known input"""
self.maxDiff = None
for dic in self.knownValuesClean:
result = parse(build(dic), unquote=True)
self.assertEqual(dic, result)
def test_parse_known_values(self):
"""parse should give known result with known input (quoted)"""
self.maxDiff = None
for dic in self.knownValues:
result = parse(build(dic))
self.assertEqual(dic, result)
def test_parse_known_values_clean_with_unicode(self):
"""parse should give known result with known input"""
self.maxDiff = None
encoding = 'utf-8' if sys.version_info[0] == 2 else None
for dic in self.knownValuesClean + self.knownValuesCleanWithUnicode:
result = parse(build(dic, encoding=encoding), unquote=True, encoding=encoding)
self.assertEqual(dic, result)
def test_parse_known_values_with_unicode(self):
"""parse should give known result with known input (quoted)"""
self.maxDiff = None
encoding = 'utf-8' if sys.version_info[0] == 2 else None
for dic in self.knownValues + self.knownValuesWithUnicode:
result = parse(build(dic, encoding=encoding), encoding=encoding)
self.assertEqual(dic, result)
def test_parse_unicode_input_string(self):
"""https://github.com/bernii/querystring-parser/issues/15"""
qs = u'first_name=%D8%B9%D9%84%DB%8C'
expected = {u'first_name': u'\u0639\u0644\u06cc'}
self.assertEqual(parse(qs.encode('ascii')), expected)
self.assertEqual(parse(qs), expected)
def test_build(self):
result = build(self.request_data)
self.assertEquals(parse(result), self.request_data)
def test_end_to_end(self):
self.maxDiff = None
querystring = build(self.request_data)
result = parse(querystring)
self.assertEquals(result, self.request_data)
def test_end_to_end(self):
parsed = parse('a[]=1&a[]=2')
result = build(parsed)
self.assertEquals(result, "a[]=1&a[]=2")
def test_parse_normalized(self):
result = parse(build(self.knownValues), normalized=True)
self.assertEqual(self.knownValuesNormalized, result)
def interpret(text : str,
source : 'file',
output : 'file',
stdout : 'file' = ostream):
root = parse(text, source.read())
states = InterpreterStates(root, output, stdout)
for expression in root:
states.evaluate(expression)
def convert(jsonfile, outfile):
f = open(jsonfile, 'r')
jsonstr = f.read()
graph = parser.parse(jsonstr)
layout.layout(graph["node"])
svg = render.render(graph)
of = open(outfile, 'w')
of.write(svg)
def __init__(self, content=None, base_path=None, base_uri=None):
if content is not None:
self.data = parser.parse(content)
else:
self.data = {}
self._base_uri = base_uri
self._initialize_attributes()
self.base_path = base_path
def main():
parser = argparse.ArgumentParser(description='Get approx solution of give TSP')
parser.add_argument('file_name', help='graph data file')
parser.add_argument('-v', action='store_true', dest='verbose')
parser.add_argument('--batch-size', dest='batch_size', type=int, default=200,
help='size of partial graph')
parser.add_argument('--iter-num1', dest='iter_num1', type=int, default=200,
help='iteration number of phase1')
parser.add_argument('--iter-num2', dest='iter_num2', type=int, default=100,
help='iteration number of phase2 and 3')
parser.add_argument('--queue-size', dest='queue_size', type=int, default=1000,
help='queue size')
parser.add_argument('--neighbor-size1', dest='neighbor_size1', type=int, default=300,
help='neighbor size of phase1')
parser.add_argument('--neighbor-size2', dest='neighbor_size2', type=int, default=100,
help='neighbor size of phase2 and 3')
args = parser.parse_args()
graph = parse(args.file_name)
if not graph:
print('- invalid graph file')
exit(1)
if args.verbose: print('+ Phase1: Calculating Partial Optimized Tour')
tour_list = get_partial_tour(args, graph)
if args.verbose: print('+ Phase2: Merging 2-approx Tour')
init_tour = merge_tour(args, graph, tour_list)
if args.verbose: print('+ Phase3: Optimizing Solution using Local Search')
tour, cost = optimize_tour(args, graph, init_tour)
if args.verbose: print('+ Verifying Solution')
for i in range(graph.vertex_num()):
if i not in tour:
print('- Verify Failed: Vertex %s not in Tour' % i)
with open('solution.csv', 'w') as f:
for item in tour:
f.write("%s\n" % (item+1))
print('+ Done! Cost: %s, Optimal Tour was saved to solution.csv' % cost)