本文整理汇总了Python中reader.Reader.read方法的典型用法代码示例。如果您正苦于以下问题:Python Reader.read方法的具体用法?Python Reader.read怎么用?Python Reader.read使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类reader.Reader
的用法示例。
在下文中一共展示了Reader.read方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: evaluate
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def evaluate(expr):
reader = Reader(expr)
try:
exprs = reader.read()
except Exception, e:
print e
return
示例2: load_lisp_core
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def load_lisp_core(filename="core.lisp"):
# Load up and evaluate core.lisp
f = open(filename)
reader = Reader(f.read(), filename)
f.close()
for expr in reader.read():
expr.evaluate(core.scope)
示例3: main
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def main(size, path):
checker = Checker(size)
reader = Reader(checker, size)
data = reader.read("data\\" + path)
solver = Solver(checker, size)
try:
return solver.solve(data)
except Exception as e:
return str(e)
示例4: evaluate_file
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def evaluate_file(filename):
try:
f = open(filename)
except IOError:
print "Cannot open file %s" % repr(filename)
return
reader = Reader(f.read())
f.close()
try:
exprs = reader.read()
except Exception, e:
print e
return
示例5: main_test
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def main_test():
reader = Reader()
retainer = Retainer()
params = reader.read()
api_targets = []
for name, param in params.items():
parser = Parser(name, param)
api_targets.append(parser)
for target in api_targets:
creater = Creater(target)
api_parameters = creater.create()
retainer.insert(target.name, api_parameters)
retainer.close()
示例6: read
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def read(path):
process_data = Reader.read(path)
process_data = process_data.split("\n")
return_data = []
if (len(process_data) == 0):
print "Empty file at "+path
return []
else:
for line in process_data:
if(line.strip() != ""):
c_index = line.find(",")
if(c_index > -1):
line = line.split(",")
return_data.append(map(str.strip, line))
else:
return_data.append(line.strip())
return return_data
示例7: repl
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
def repl():
global EOFError
source = ""
while True:
# Get a new source line
try:
if source == "":
source = raw_input("=> ") + '\n'
else:
source += raw_input() + '\n'
except KeyboardInterrupt, EOFError:
break
# Read the source line
reader = Reader(source)
try:
exprs = reader.read()
except EOFError:
# Need more input
continue
except Exception, e:
print e
source = ""
continue
示例8: str
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
for mention in i.getMentionsList():
left = mention[0]
right = mention[1]
print docText[left:right] + str(mention), "|",
print "\n"
raw_input("==========================<Press enter to continue>==========================")
verbose = True # True: prints the details of the clusters after each pass; False: no such printing
filename = raw_input("Enter name of input file: ")
mentionfile = raw_input("Enter name of mentions file: ")
reader = Reader("input/")
filler = InformationFiller()
doc = reader.read(filename, mentionfile)
docText = doc.getText()
filler.process(doc)
if verbose:
print "\nInitially:\n"
printClusterDetails()
sieve = ExactMatchSieve()
sieve.process(doc)
if verbose:
print "\nAfter Pass 1:\n"
printClusterDetails()
sieve = PreciseConstructsSieve()
sieve.process(doc)
if verbose:
示例9: Parser
# 需要导入模块: from reader import Reader [as 别名]
# 或者: from reader.Reader import read [as 别名]
class Parser(object):
"""Parse PDS files into a dictionary.
Instances of this module are reusable.
Parsing a PDS data product results in a dictionary whose keys correspond to unchanged PDS labels --
i.e. label['RECORD_TYPE'] is not the same as label['record_type'].
Grouped labels are stored as nested dictionaries, nesting may be arbitrarily deep.
Internally, these groups are called *containers* and must be in {OBJECT, GROUP}.
This module makes heavy use of assertions to find bugs and detect poorly formatted files.
As usual, when an assertion fails an AssertionError is raised. This type of behavior may not be desired
or expected, since it will halt execution, especially when addressing multiple files in a production environment.
Assertions are not checked in -O mode, use that to temporarily override this behavior.
Future versions may do away with assertions altogether and utilize the logging facility.
Logging is not very mature at this stage, but usable.
Although this feature is not supported at this time, a future version may perform automatic type conversion
as per the PDS specification.
Simple Usage Example
>>> from parser import Parser
>>> pdsParser = Parser()
>>> for f in ['file1.lbl', 'file2.lbl']:
>>> labelDict = pdsParser.parse(open(f, 'rb'))
"""
def __init__(self, log=None):
"""Initialize a reusable instance of the class."""
super(Parser, self).__init__()
self._reader = Reader()
self.log = log
if log:
self._init_logging()
def _init_logging(self):
"""Initialize logging."""
# Set the message format.
format = logging.Formatter("%(levelname)s:%(name)s:%(asctime)s:%(message)s")
# Create the message handler.
stderr_hand = logging.StreamHandler(sys.stderr)
stderr_hand.setLevel(logging.DEBUG)
stderr_hand.setFormatter(format)
# Create a handler for routing to a file.
logfile_hand = logging.FileHandler(self.log + '.log')
logfile_hand.setLevel(logging.DEBUG)
logfile_hand.setFormatter(format)
# Create a top-level logger.
self.log = logging.getLogger(self.log)
self.log.setLevel(logging.DEBUG)
self.log.addHandler(logfile_hand)
self.log.addHandler(stderr_hand)
self.log.debug('Initializing logger')
def __str__(self):
"""Print a friendly, user readable representation of an instance."""
strItems = []
strItems.append('PDSParser: %s' % (repr(self),))
return '\n'.join(strItems)
def parse(self, source):
"""Parse the source PDS data."""
if self.log: self.log.debug("Parsing '%s'" % (source.name,))
self._labels = self._parse_header(source)
if self.log: self.log.debug("Parsed %d top-level labels" % (len(self._labels)))
return self._labels
def _parse_header(self, source):
"""Parse the PDS header.
For grouped data, supported containers belong to {'OBJECT', 'GROUP'}.
Unidentified containers will be parsed as simple labels and will not create a child dictionary.
"""
if self.log: self.log.debug('Parsing header')
CONTAINERS = {'OBJECT':'END_OBJECT', 'GROUP':'END_GROUP'}
CONTAINERS_START = CONTAINERS.keys()
CONTAINERS_END = CONTAINERS.values()
root = ParserNode({}, None)
currentNode = root
expectedEndQueue = []
for record in self._reader.read(source):
k, v = record[0], record[1]
assert k == k.strip() and v == v.strip(), ('Found extraneous whitespace near %s and %s') % (k, v)
if k in CONTAINERS_START:
expectedEndQueue.append((CONTAINERS[k], v))
currentNode = ParserNode({}, currentNode)
#print expectedEndQueue
elif k in CONTAINERS_END:
try:
expectedEnd = expectedEndQueue.pop()
newParent = currentNode.parent
newParent.children[v] = currentNode.children
currentNode = newParent
#.........这里部分代码省略.........