本文整理汇总了Python中xml.etree.ElementTree.fromstringlist方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.fromstringlist方法的具体用法?Python ElementTree.fromstringlist怎么用?Python ElementTree.fromstringlist使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.fromstringlist方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: split_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def split_file(filename):
# we want you to split the input file into separate files
# each containing a single patent.
# As a hint - each patent declaration starts with the same line that was causing the error
# The new files should be saved with filename in the following format:
# "{}-{}".format(filename, n) where n is a counter, starting from 0.
output = []
data = {}
f = open(filename)
count = 0
file_number = 0
# import pprint
# pprint.pprint(f.readlines())
output.append(f.readline())
for line in f.readlines():
if line.startswith("<?xml"):
data["patent.data-{}".format(file_number)] = output
root = ET.fromstringlist(output)
# print ""
# print root.tag
# print root.attrib
#
# for child in root:
# print(child.tag, child.attrib)
tree = ET.ElementTree(root)
tree.write("patent.data-{}".format(file_number), encoding = 'UTF-8')
output = []
file_number += 1
output.append(line)
data["patent.data-{}".format(file_number)] = output
root = ET.fromstringlist(output)
tree = ET.ElementTree(root)
tree.write("patent.data-{}".format(file_number), encoding = 'UTF-8')
#import pprint
#pprint.pprint(data)
# return data
pass
示例2: from_stringlist
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def from_stringlist(sequence):
try:
element = ElementTree.fromstringlist(sequence)
except ElementTree.ParseError as e:
raise VaspParseError(e)
return from_element(element)
示例3: main
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def main():
s = xmlrpc.client.ServerProxy('http://localhost:8000')
lines = []
for line in sys.stdin:
if line.strip():
lines.append(line.strip())
corpus = ET.fromstringlist(lines)
for sentence in corpus:
sentnum = sentence.attrib['ref']
tuples = lexsel_util.get_tuples(sentence)
surface = [tup[1] for tup in tuples]
dprint("[SURFACE]", " ".join(surface))
answers = s.label_sentence(tuples)
dprint("[ANSWERS]", answers)
## all the NODE elements in the tree that have a SYN underneath
target_nodes = sentence.findall(".//NODE/SYN/..")
changed = False
for node in target_nodes:
changed_here = make_decision(node, answers)
if changed_here:
changed = True
if changed:
dprint("[CLASSIFIERSENTENCE]", sentnum)
print(ET.tostring(corpus,encoding="unicode"))
示例4: log_response_error
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def log_response_error(response_error):
"""
@type response_error: owncloud.ResponseError
"""
message = response_error.get_resource_body()
if message[:38] == '<?xml version="1.0" encoding="utf-8"?>':
import xml.etree.ElementTree as ElementTree
response_exception = ''
response_message = ''
response = message[39:]
root_element = ElementTree.fromstringlist(response)
if root_element.tag == '{DAV:}error':
for child in root_element:
if child.tag == '{http://sabredav.org/ns}exception':
response_exception = child.text
if child.tag == '{http://sabredav.org/ns}message':
response_message = child.text
if response_exception != '':
message = 'SabreDAV Exception: %s - Message: %s' % (response_exception, response_message)
logger.error('Unexpected response: Status code: %i - %s' % (response_error.status_code, message))
logger.info('Full Response: %s' % (response_error.get_resource_body()))
示例5: __parse_linear_base64
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def __parse_linear_base64(self) -> Element:
"""Original parser will fail in case such email
```
Content-Type: text/plain\r\n
Content-Transfer-Encoding: base64\r\n\r\n
PHByZW...==\r\n
...
...==\r\n
```
as a workaround getting raw body and split by '\n' and parse xml
as string list
:return: Element
"""
def decode_payload(data: Any) -> Generator:
"""
:return: generator
"""
if isinstance(data, (str, bytes)):
data = data.splitlines()
for line in filter(None, data):
if line[-2:] in ['==', b'=='] or line[-1] in ['+', b'+']:
yield body_decode(line)
else:
yield line
return ElementTree.fromstringlist(
decode_payload(self.__message.get_payload())
)
示例6: split_file
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def split_file(filename):
"""
Split the input file into separate files, each containing a single patent.
As a hint - each patent declaration starts with the same line that was
causing the error found in the previous exercises.
The new files should be saved with filename in the following format:
"{}-{}".format(filename, n) where n is a counter, starting from 0.
"""
data=[]
results=[]
n=0
with open(filename,"rb") as f:
flines=f.readlines()
for i in range(len(flines)):
line=flines[i]
if line.startswith("<?xml") and len(data) >0:
results.append(data)
data=[]
else:
data.append(line)
if (i==len(flines)-1):
results.append(data)
for res in results:
tre=ET.ElementTree(ET.fromstringlist(res))
newfile="{}-{}".format(filename,n)
n+=1
tre.write(newfile,xml_declaration=True,method="xml",encoding="UTF-8")
开发者ID:shrutisingh15,项目名称:Data_Wrangling_With_MongoDB,代码行数:33,代码来源:Quiz_Solution-ProcessingPatents.py
示例7: parse
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def parse(self, ofx):
try:
for line in ofx.splitlines():
if line.strip() == "":
break
header, value = line.split(":")
self.headers[header] = value
except ValueError:
pass
finally:
if "OFXHEADER" not in self.headers:
self.headers["OFXHEADER"] = "100"
if "VERSION" not in self.headers:
self.headers["VERSION"] = "102"
if "SECURITY" not in self.headers:
self.headers["SECURITY"] = "NONE"
if "OLDFILEUID" not in self.headers:
self.headers["OLDFILEUID"] = "NONE"
if "NEWFILEUID" not in self.headers:
self.headers["NEWFILEUID"] = "NONE"
try:
tags = ofx.split("<")
if len(tags) > 1:
tags = ["<" + t.strip() for t in tags[1:]]
heirarchy = []
can_open = True
for i, tag in enumerate(tags):
gt = tag.index(">")
if tag[1] != "/":
# Is an opening tag
if not can_open:
tags[i - 1] = tags[i - 1] + "</" + \
heirarchy.pop() + ">"
can_open = True
tag_name = tag[1:gt].split()[0]
heirarchy.append(tag_name)
if len(tag) > gt + 1:
can_open = False
else:
# Is a closing tag
tag_name = tag[2:gt].split()[0]
if tag_name not in heirarchy:
# Close tag with no matching open, so delete it
tags[i] = tag[gt + 1:]
else:
# Close tag with matching open, but other open
# tags that need to be closed first
while(tag_name != heirarchy[-1]):
tags[i - 1] = tags[i - 1] + "</" + \
heirarchy.pop() + ">"
can_open = True
heirarchy.pop()
self.xml = ET.fromstringlist(tags)
self.load_from_xml(self, self.xml)
except Exception:
raise InvalidOFXStructureException
示例8: fill_dictionary
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def fill_dictionary(cls, result_dir):
"""
Parsed files.xml and symbols.xml and fill dictionary
:return:
"""
XML_FILES = ['files.xml', 'symbols.xml']
results_dict = {}
for tag in settings.CHECKER_TAGS:
results_dict[tag] = []
for file_name in [os.path.join(result_dir, x) for x in XML_FILES]:
logger.info('Processing %s file.', file_name)
try:
with open(file_name, "r") as f:
lines = f.readlines()
lines.insert(0, '<pkgdiff>')
lines.append('</pkgdiff>')
pkgdiff_tree = ElementTree.fromstringlist(lines)
for tag in settings.CHECKER_TAGS:
for pkgdiff in pkgdiff_tree.findall('.//' + tag):
results_dict[tag].extend([x.strip() for x in pkgdiff.text.strip().split('\n')])
except IOError:
continue
return results_dict
示例9: main
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def main():
# ignore SIGCHLD, prevent the zombie apocalypse
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
utils.drop_privileges()
bad_regex = re.compile("[,()]+") # avoid forbidden by TSD symbols
while True:
try:
if vstats == "all":
stats = subprocess.Popen(
["varnishstat", "-1", "-x"],
stdout=subprocess.PIPE,
)
else:
fields = ",".join(vstats)
stats = subprocess.Popen(
["varnishstat", "-1", "-f" + fields, "-x"],
stdout=subprocess.PIPE,
)
except OSError, e:
# Die and signal to tcollector not to run this script.
sys.stderr.write("Error: %s\n" % e)
sys.exit(13)
metrics = ""
for line in stats.stdout.readlines():
metrics += line
metrics = ET.fromstringlist(metrics)
timestamp = ""
if use_varnishstat_timestamp:
pattern = "%Y-%m-%dT%H:%M:%S"
timestamp = int(time.mktime(time.strptime(metrics['timestamp'], pattern)))
else:
timestamp = time.time()
for stat in metrics.findall('stat'):
tags = ""
k = stat.findtext('name')
if None == bad_regex.search(k):
stattype = stat.findtext('type')
if stattype == None:
metric_name = metric_prefix + "." + k
elif stattype == "LCK":
metric_name = metric_prefix + ".locks." + k
ident = stat.findtext('ident')
tags = "ident=" + ident
elif stattype == "SMA":
metric_name = metric_prefix + ".storage." + k
ident = stat.findtext('ident')
tags = "ident=" + ident
else:
continue
print "%s %d %s %s" % \
(metric_name, timestamp, stat.findtext('value'), tags)
sys.stdout.flush()
time.sleep(interval)
示例10: export_as_TEI
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def export_as_TEI (self, request, queryset):
entries = ['<listBibl>']
entries.extend(queryset.values_list('tei_entry', flat=True))
entries.append('</listBibl>')
root = ElementTree.fromstringlist(entries)
tei = ElementTree.tostring(root, encoding='utf-8')
response = HttpResponse(tei, mimetype='text/xml')
return response
示例11: tagTimeContent
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def tagTimeContent(self, tagname, time):
self.tree = ET.fromstringlist(self.makeTimeRequest(self, time))
for elt in self.tree.iter():
if elt.tag == str(tagname):
self.tagvalue = elt.text.strip()
return self.tagvalue
示例12: __parseLines
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def __parseLines(self,lines):
variables = {}
result = ET.fromstringlist(lines)
for element in list(result):
variables[element.tag]=element.text
return variables
示例13: get_totals
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def get_totals(boundingbox):
search = flickr.photos_search(min_upload_date='2013-01-01',
bbox=boundingbox,
accuracy=16,
extras='geo,date_taken,tags')
root = ET.fromstringlist(search, parser=None)
for child in root:
print child.tag, child.attrib
示例14: _run_info_parser
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def _run_info_parser(run_info):
result = dict()
if len(run_info['result']) > 0:
root = ET.fromstringlist(run_info['result'])
result = dict(
reads=[r.attrib for r in root.iter('Read')],
fc_layout=[fc.attrib for fc in root.iter('FlowcellLayout')],
)
return result
示例15: parse_XML
# 需要导入模块: from xml.etree import ElementTree [as 别名]
# 或者: from xml.etree.ElementTree import fromstringlist [as 别名]
def parse_XML(self, output, returncode, isTimeout):
#an empty tag cannot be parsed into a tree
def sanitizeXML(s):
return s.replace("<>", "<emptyTag>") \
.replace("</>", "</emptyTag>")
try:
tree = ET.fromstringlist(map(sanitizeXML, output))
status = tree.findtext('cprover-status')
if status is None:
def isErrorMessage(msg):
return msg.get('type', None) == 'ERROR'
messages = list(filter(isErrorMessage, tree.getiterator('message')))
if messages:
# for now, use only the first error message if there are several
msg = messages[0].findtext('text')
if msg == 'Out of memory':
status = 'OUT OF MEMORY'
elif msg:
status = 'ERROR (%s)'.format(msg)
else:
status = 'ERROR'
else:
status = 'INVALID OUTPUT'
elif status == "FAILURE":
assert returncode == 10
reason = tree.find('goto_trace').find('failure').findtext('reason')
if not reason:
reason = tree.find('goto_trace').find('failure').get('reason')
if 'unwinding assertion' in reason:
status = result.RESULT_UNKNOWN
else:
status = result.RESULT_FALSE_REACH
elif status == "SUCCESS":
assert returncode == 0
if "--no-unwinding-assertions" in self.options:
status = result.RESULT_UNKNOWN
else:
status = result.RESULT_TRUE_PROP
except Exception:
if isTimeout:
# in this case an exception is expected as the XML is invalid
status = 'TIMEOUT'
elif 'Minisat::OutOfMemoryException' in output:
status = 'OUT OF MEMORY'
else:
status = 'INVALID OUTPUT'
logging.exception("Error parsing CBMC output for returncode %d" % (returncode))
return status