本文整理汇总了Python中xml.etree.ElementTree.ElementTree类的典型用法代码示例。如果您正苦于以下问题:Python ElementTree类的具体用法?Python ElementTree怎么用?Python ElementTree使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ElementTree类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main():
parser = argparse.ArgumentParser(description="convert Mitsuba scenes to appleseed format.")
parser.add_argument("input_file", metavar="input-file", help="Mitsuba scene (*.xml)")
parser.add_argument("output_file", metavar="output-file", help="appleseed scene (*.appleseed)")
args = parser.parse_args()
# Create a log target that outputs to stderr, and binds it to the renderer's global logger.
# Eventually you will want to redirect log messages to your own target.
# For this you will need to subclass appleseed.ILogTarget.
log_target = asr.ConsoleLogTarget(sys.stderr)
# It is important to keep log_target alive, as the global logger does not
# take ownership of it. In this example, we do that by removing the log target
# when no longer needed, at the end of this function.
asr.global_logger().add_target(log_target)
asr.global_logger().set_verbosity_level(asr.LogMessageCategory.Warning)
tree = ElementTree()
try:
tree.parse(args.input_file)
except IOError:
fatal("Failed to load {0}".format(args.input_file))
project = convert(tree)
asr.ProjectFileWriter().write(project, args.output_file,
asr.ProjectFileWriterOptions.OmitHandlingAssetFiles)
开发者ID:dcoeurjo,项目名称:appleseed,代码行数:27,代码来源:mitsuba2appleseed.py
示例2: guess_location
def guess_location(in_xml, in_fasta, write_out = False):
"""Tries to guess the genomic location of a fragment."""
name, seq = fasta_iter(in_fasta).next()
parts = name.split('|')
if len(parts) == 3:
return
starts = []
seq_len = len(seq)
try:
tree = ElementTree(file = in_xml)
for it in tree.getiterator('Iteration'):
start_elem = it.find('Iteration_hits/Hit/Hit_hsps/Hsp/Hsp_hit-from')
name_elem = it.find('Iteration_query-def')
if start_elem is not None:
tstart = int(name_elem.text.split('_')[1])
starts.append(int(start_elem.text)-tstart)
except ExpatError:
return None
if starts:
start = max(sum(starts)/len(starts), 1)
if write_out:
with open(in_fasta, 'w') as handle:
handle.write('>%s|%i|%i\n%s\n' % (name, start, start+seq_len, seq))
return start
开发者ID:JudoWill,项目名称:LinkageAnalysis,代码行数:26,代码来源:NCBIUtils.py
示例3: add_text_layer
def add_text_layer(self,pdf, hocrfile, page_num,height, dpi):
"""Draw an invisible text layer for OCR data"""
p1 = re.compile('bbox((\s+\d+){4})')
p2 = re.compile('baseline((\s+[\d\.\-]+){2})')
hocr = ElementTree()
hocr.parse(hocrfile)
logging.debug(xml.etree.ElementTree.tostring(hocr.getroot()))
for c in hocr.getroot(): # Find the <body> tag
if c.tag != 'body':
continue
for page in c: # Each child in the body is a page tag
if (page.attrib['class'] != "ocr_page"):
assert ("Why is this hocr not paging properly??")
if page.attrib['id'] == 'page_%d' %(page_num):
break
for line in page.findall(".//{http://www.w3.org/1999/xhtml}span"):
#for line in page.findall(".//span"):
if line.attrib['class'] != 'ocr_line':
continue
linebox = p1.search(line.attrib['title']).group(1).split()
try:
baseline = p2.search(line.attrib['title']).group(1).split()
except AttributeError:
baseline = [ 0, 0 ]
linebox = [float(i) for i in linebox]
baseline = [float(i) for i in baseline]
for word in line:
if word.attrib['class'] != 'ocrx_word':
continue
word_text = []
for child in word.iter():
if child.text:
word_text.append(child.text)
word.text = ' '.join(word_text)
logging.debug(word.text)
#for child in word:
#if child.tag:
#word.text = child.text
if word.text is None:
continue
font_width = pdf.stringWidth(word.text.strip(), 'invisible', 8)
if font_width <= 0:
continue
box = p1.search(word.attrib['title']).group(1).split()
box = [float(i) for i in box]
b = self.polyval(baseline, (box[0] + box[2]) / 2 - linebox[0]) + linebox[3]
text = pdf.beginText()
text.setTextRenderMode(3) # double invisible
text.setFont('invisible', 8)
text.setTextOrigin(box[0] * 72 / dpi, height - b * 72 / dpi)
box_width = (box[2] - box[0]) * 72 / dpi
text.setHorizScale(100.0 * box_width / font_width)
text.textLine(word.text.strip())
#logging.debug( "Pg%s: %s" % (page_num,word.text.strip()))
pdf.drawText(text)
开发者ID:lol84,项目名称:pypdfocr,代码行数:60,代码来源:pypdfocr_pdf.py
示例4: read_config
def read_config(config_file):
tree = ElementTree()
tree.parse(config_file)
root = tree.getroot()
server = root.attrib['name']
server_vm = root.attrib['virtual_machine']
protocals = root.getchildren()
acnt = [0,0,0,0]
cur_datetime = datetime.now()
guacamole_client_list=[]
for protocal in protocals:
pro_name = protocal.attrib['name']
clients = protocal.getchildren()
cnt = 0
for client in clients:
cnt+=1
client_name = client.attrib['name']
client_host = client[0].text
client_vm = client[1].text
guacamoleClientInfo = GuacamoleClientInfo('','',server,client_name,pro_name,client_host,client_vm,0,cur_datetime)
guacamole_client_list.append(guacamoleClientInfo)
if pro_name=='vnc':
acnt[0] = cnt
elif pro_name=='vnc-read-only':
acnt[1] = cnt
elif pro_name=='ssh':
acnt[2] = cnt
else:
acnt[3] = cnt
guacamoleServerLoad = GuacamoleServerLoad(server,server_vm,acnt[0],acnt[1],acnt[2],acnt[3],sum(acnt),cur_datetime,0)
guacamoleServerLoad.guacamole_client_info = guacamole_client_list
return guacamoleServerLoad
开发者ID:czx0619,项目名称:LABOSS,代码行数:33,代码来源:restserver.py
示例5: qrcode_render
def qrcode_render(content, size, padding, version, em, ec, newline, parent):
if newline:
content = content.replace("\\n", "\n")
content = content.replace("\\r", "\r")
# Generate QR Code - call web service
qrcode = qrcode_generate(content, size, padding, version, em, ec)
#if not result:
# return
# Parse SVG and draw elements to the workspace
tree = ElementTree()
tree.parse(StringIO(qrcode))
root = tree.getroot()
xmlns = "{http://www.w3.org/2000/svg}"
modules = list(root.getiterator(xmlns + "rect"))
for m in modules:
# <rect x="32" y="32" width="8" height="8" style="fill:rgb(0,0,0);" />
x = m.attrib["x"]
y = m.attrib["y"]
w = m.attrib["width"]
h = m.attrib["height"]
style = m.attrib["style"]
qrcode_draw_module((w,h), (x,y), style, parent)
开发者ID:BackupGGCode,项目名称:qr-code-plugins,代码行数:25,代码来源:render_barcode_qrcode.py
示例6: _validate_pomdesc
def _validate_pomdesc(fd):
"""check Maven POM for title, description and organization"""
NS = '{http://maven.apache.org/POM/4.0.0}'
PROJECT_NAME_REGEX = re.compile(r'^[a-z][a-z0-9-]*$')
tree = ElementTree()
try:
elem = tree.parse(fd)
except Exception as e:
_detail('%s: %s' % (e.__class__.__name__, e))
return False
# group = elem.findtext(NS + 'groupId')
name = elem.findtext(NS + 'artifactId')
# ver = elem.findtext(NS + 'version')
title = elem.findtext(NS + 'name')
if title == '${project.artifactId}':
title = name
description = elem.findtext(NS + 'description')
organization = elem.findtext(NS + 'organization/' + NS + 'name')
if not name or not PROJECT_NAME_REGEX.match(name):
_detail('has invalid name (does not match %s)' % PROJECT_NAME_REGEX.pattern)
if not title:
_detail('is missing title (<name>...</name>)')
elif title.lower() == name.lower():
_detail('has same title as name/artifactId')
if not description:
_detail('is missing description (<description>..</description>)')
elif len(description.split()) < 3:
_detail('has a too short description')
if not organization:
_detail('is missing organization (<organization><name>..</name></organization>)')
return not VALIDATION_DETAILS
开发者ID:jmcs,项目名称:codevalidator,代码行数:33,代码来源:codevalidator.py
示例7: patch
def patch(pom_file, version):
'''Updates the version in a POM file. We need to locate //project/parent/version, //project/version and
//project/properties/project-version and replace the contents of these with the new version'''
if settings['verbose']:
prettyprint("Patching %s" % pom_file, Levels.DEBUG)
tree = ElementTree()
tree.parse(pom_file)
need_to_write = False
tags = []
tags.append(get_parent_version_tag(tree))
tags.append(get_project_version_tag(tree))
tags.append(get_properties_version_tag(tree))
for tag in tags:
if tag != None and "-SNAPSHOT" in tag.text:
if settings['verbose']:
prettyprint("%s is %s. Setting to %s" % (str(tag), tag.text, version), Levels.DEBUG)
tag.text=version
need_to_write = True
if need_to_write:
# write to file again!
write_pom(tree, pom_file)
return True
else:
if settings['verbose']:
prettyprint("File doesn't need updating; nothing replaced!", Levels.DEBUG)
return False
开发者ID:jnan77,项目名称:infinispan,代码行数:29,代码来源:release.py
示例8: test_separate_timer_test_case
def test_separate_timer_test_case(self):
"""Check that the elapsed time for each test is set separately.
This test encodes a bug in which the elapsed time of the most recently
run test was reported as the elapsed time for each test.
"""
# reset runner to record elapsed times
self.runner = xmlrunner.XMLTestRunner(output=self.stream,
stream=self.fake_stream, elapsed_times=True)
self.runner.run(unittest.makeSuite(testcases.SeparateTimerTestCase))
f = StringIO(self.stream.getvalue())
try:
tree = ElementTree(file=f)
(first, second) = tree.findall('testcase')
# allow 25ms beyond the sleep() time for garbage collection
self.assertEqual('test_run_for_100ms', first.attrib['name'])
first_time = float(first.attrib['time'])
self.assertTrue(0.100 <= first_time < 0.125,
'expected about 0.1s. actual: %ss' % first_time)
self.assertEqual('test_run_for_50ms', second.attrib['name'])
second_time = float(second.attrib['time'])
self.assertTrue(0.050 <= second_time < 0.075,
'expected about 0.05s. actual: %ss' % second_time)
finally:
f.close()
开发者ID:cfoote,项目名称:unittest-xml-reporting,代码行数:30,代码来源:testsuite.py
示例9: __init__
def __init__(self):
#Running gtk.Window's init method
super(MainWindow, self).__init__()
self.set_size_request(280,700)
#connect gui close button to quit signal
self.connect("destroy", gtk.main_quit)
#The table is the real gui, the window just holds it.
#Gizmos are added to the table, not the window.
self.table = gtk.Table(12,4,True)
#----------------------------------
etree = ElementTree()
etree.parse("launchers.xml")
#XML insists on nesting everything a dozen times
launchers = etree.find("launchers")
for i, launcherConfig in enumerate(launchers.getchildren()):
launcher = gtk.Button()
launcher.set_label(launcherConfig.find("name").text)
self.table.attach(launcher, 0, 1, i, i+1)
#-----------------------------------
#add the table to the window
self.add(self.table)
#if you don't show or show_all, no gui
self.show_all()
开发者ID:free-code,项目名称:omniDOCK,代码行数:27,代码来源:window_and_table2.py
示例10: getWeatherData
def getWeatherData(self, location):
"""
"""
## if cached
yymmddhh = datetime.datetime.now().replace(tzinfo=UTC).astimezone(JST).strftime('%Y%m%d%H')
key = str(yymmddhh + "_" + location)
mc = Caching.MemcacheStore()
data = mc.get(key)
if data:
return data
data = []
patt = re.compile(u"^.* \[ ([0-9]+).* \] ([0-9.]+).*$")
cur = self._rdb.cursor(MySQLdb.cursors.DictCursor)
cur.execute("""SELECT sht.prefid AS prefid FROM area a
JOIN area_has_state ahs ON (a.areaid=ahs.areaid)
JOIN state s ON (s.stateid=ahs.stateid)
JOIN state_has_tenkijpPref sht ON (s.stateid=sht.stateid)
WHERE a.location=%s""", (location,))
row = cur.fetchone()
cur.close()
## temperature
fh = urllib2.urlopen(WEATHERAPI % row['prefid'])
rss = ElementTree(file=fh)
items = rss.findall('.//item')
for item in items:
title = item.find('title').text
data.append({'title':title})
mc.set(key, data)
return data
开发者ID:hagaeru3sei,项目名称:tidegraph,代码行数:33,代码来源:main.py
示例11: parse_fzp
def parse_fzp(self, fzp_file):
""" Parse the Fritzing component file """
tree = ElementTree(file=fzp_file)
try:
prefix = tree.find('label').text
except AttributeError:
pass
else:
self.component.add_attribute('_prefix', prefix)
symbol = Symbol()
self.component.add_symbol(symbol)
self.body = SBody()
symbol.add_body(self.body)
self.cid2termid.update(self.parse_terminals(tree))
self.terminals.update(self.cid2termid.values())
layers = tree.find('views/schematicView/layers')
if layers is None:
self.image = None
else:
self.image = layers.get('image')
开发者ID:EasyPCB,项目名称:schematic-file-converter,代码行数:26,代码来源:fritzing.py
示例12: parse_config
def parse_config(name):
tree = ElementTree()
tree.parse(name)
items = []
for item in list(tree.getroot()):
items.append(process_element(item))
return items
开发者ID:dahool,项目名称:regeer,代码行数:7,代码来源:functions.py
示例13: import_opml
def import_opml(opml_file):
tree = ElementTree()
tree.parse(opml_file)
outlines = tree.findall(".//outline")
tag = None
# TODO: fix this for all opml formats
for o in outlines:
xmlurl = None
try:
xmlurl = o.attrib['xmlUrl']
except:
tag = o.attrib['text']
if xmlurl:
try:
# print "inserting ", tag, o.attrib['xmlUrl'], o.attrib['htmlUrl'], o.attrib['text'], tag
f = {
'_id': str(uuid.uuid1()),
'title': o.attrib['text'],
'url': o.attrib['xmlUrl'],
'web_url': o.attrib['htmlUrl'],
'tag': tag,
}
db.feeds.update({'url': f['url']}, f, True)
except:
pass
开发者ID:mpmedia,项目名称:neko,代码行数:26,代码来源:neko.py
示例14: parse_scenes_info
def parse_scenes_info(scenes_info_file, model_dirs, ply_paths):
print 'Parsing: ' + scenes_info_file
#parse xml file
bof_tree = ElementTree();
bof_tree.parse(scenes_info_file);
scenes_elm = bof_tree.getroot().findall('scene');
if scenes_elm is None:
print "Invalid bof info file: No scenes element"
sys.exit(-1);
#find scene paths
for s in range(0, len(scenes_elm)):
path = scenes_elm[s].get("output_dir");
ply_file = scenes_elm[s].get("ply_path");
if path is None:
print "Invalid info file: Error parsing scene path"
sys.exit(-1);
if ply_file is None:
print "Invalid info file: Error parsing ply_file"
sys.exit(-1);
model_dirs.append(path);
ply_paths.append(ply_file);
开发者ID:mirestrepo,项目名称:voxels-at-lems,代码行数:30,代码来源:create_scene_from_ply_batch.py
示例15: parse_shed_tool_conf
def parse_shed_tool_conf(file):
"""
Parses the xml in shed_tool_conf xml and returns a dictionary in the following format:
{
section_id: [
name:
owner:
revision:
tool_shed_url:
]
}
"""
sections = defaultdict(lambda: {})
doc = ElementTree(file=file)
for section in doc.findall("//section"):
for tool in section.findall('tool'):
sections[
section.get('id')][
tool.find('repository_name').text +
'|' +
tool.find('installed_changeset_revision').text] = {
'name': tool.find('repository_name').text,
'owner': tool.find('repository_owner').text,
'revision': tool.find('installed_changeset_revision').text,
'tool_shed_url': 'https://' +
tool.find('tool_shed').text}
return sections
开发者ID:gvlproject,项目名称:gvl.utilities,代码行数:27,代码来源:shed_tool_conf_to_yaml.py
示例16: process
def process(self, request):
"""
Process SOAP request
"""
if request.body is not None and len(request.body) > 0:
body = urllib.unquote_plus(request.body)
tree = ElementTree(file=StringIO(body))
envelope = tree.getroot()
if envelope is None:
raise InvalidRequestException('Invalid syntax')
body = envelope.find("q:Body", namespaces=namespaces)
if body is None:
raise InvalidRequestException('Invalid syntax')
soap_req = body.find("m:GetUserOofSettingsRequest",
namespaces=namespaces)
if soap_req is not None:
return self.process_get_request(soap_req)
soap_req = body.find("m:SetUserOofSettingsRequest",
namespaces=namespaces)
if soap_req is not None:
return self.process_set_request(soap_req)
raise InvalidRequestException('Unknown SOAP request')
raise InvalidRequestException('No body in request')
开发者ID:blaxter,项目名称:openchange,代码行数:27,代码来源:oof.py
示例17: as_xml
def as_xml(self):
"""XML representation of the error to be used in HTTP response.
This XML format follows the IIIF Image API v1.0 specification,
see <http://iiif.io/api/image/1.0/#error>
"""
# Build tree
spacing = ("\n" if (self.pretty_xml) else "")
root = Element('error', {'xmlns': I3F_NS})
root.text = spacing
e_parameter = Element('parameter', {})
e_parameter.text = self.parameter
e_parameter.tail = spacing
root.append(e_parameter)
if (self.text):
e_text = Element('text', {})
e_text.text = self.text
e_text.tail = spacing
root.append(e_text)
# Write out as XML document to return
tree = ElementTree(root)
xml_buf = io.BytesIO()
if (sys.version_info < (2, 7)):
tree.write(xml_buf, encoding='UTF-8')
else:
tree.write(xml_buf, encoding='UTF-8',
xml_declaration=True, method='xml')
return(xml_buf.getvalue().decode('utf-8'))
开发者ID:edsilv,项目名称:iiif,代码行数:28,代码来源:error.py
示例18: _getTVDBThumbnail
def _getTVDBThumbnail(self):
import os, time
if self.id:
# check if the file already exists
if os.path.isfile(Config['tmpdir']+self.id+'-'+Config['tvdblang']+'.xml'):
# if it is older than config['cacherenew'] days, delete the files and download again
if os.path.getctime(Config['tmpdir']+self.id+'-'+Config['tvdblang']+'.xml') < time.time()-(Config['cacherenew']*86400):
os.remove(Config['tmpdir']+self.id+'-'+Config['tvdblang']+'.xml')
if not os.path.isfile(Config['tmpdir']+self.id+'-'+Config['tvdblang']+'.xml'):
URL('http://www.thetvdb.com/api/'+Config['tvdbapikey']+'/series/'+self.id+'/all/'+Config['tvdblang']+'.xml').download(Config['tmpdir']+self.id+'-'+Config['tvdblang']+'.xml')
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
try:
tree.parse(Config['tmpdir']+self.id+'-'+Config['tvdblang']+'.xml')
if Config['posterforpilot'] == True and self.season == 1 and self.episode == 1:
series = tree.find('Series')
if series.find('poster').text:
self.thumbnail = 'http://www.thetvdb.com/banners/'+series.find('poster').text
return True
for episode in tree.findall('Episode'):
if int(episode.find('SeasonNumber').text) == self.season and int(episode.find('EpisodeNumber').text) == self.episode:
if episode.find('filename').text:
self.thumbnail = 'http://www.thetvdb.com/banners/'+episode.find('filename').text
return True
except:
pass
return False
开发者ID:godzeus,项目名称:tw-video-scraper-local,代码行数:27,代码来源:tw-video-scraper.py
示例19: prepareLCSIMFile
def prepareLCSIMFile(inputlcsim, outputlcsim, numberofevents,
trackingstrategy, inputslcio, jars = None,
cachedir = None, outputFile = None,
outputRECFile = None, outputDSTFile = None,
debug = False):
"""Writes out a lcsim file for LCSIM
Takes the parameters passed from :mod:`~ILCDIRAC.Workflow.Modules.LCSIMAnalysis`
:param string inputlcsim: name of the provided lcsim
:param string outputlcsim: name of the lcsim file on which LCSIM is going to run, defined in :mod:`~ILCDIRAC.Workflow.Modules.LCSIMAnalysis`
:param int numberofevents: Number of events to process
:param string trackingstrategy: trackingstrategy file to use, can be empty
:param inputslcio: list of slcio files on which LCSIM should run
:type inputslcio: list of strings
:param jars: list of jar files that should be added in the classpath definition
:type jars: list of strings
:param string cachedir: folder that holds the cache directory, instead of Home
:param string outputFile: File name of the output
:param string outputDSTFile: filename of the DST file
:param string outputRECFile: filename of the REC file
:param bool debug: By default set verbosity to true
:return: S_OK(string)
"""
printtext = ''
tree = ElementTree()
try:
tree.parse(inputlcsim)
except Exception, x:
print "Found Exception %s %s" % (Exception, x)
return S_ERROR("Found Exception %s %s" % (Exception, x))
开发者ID:andresailer,项目名称:ILCDIRAC,代码行数:33,代码来源:PrepareOptionFiles.py
示例20: read_xml
def read_xml(in_path):
#读取并解析xml文件
#in_path:xml路径
#return:ElementTree
tree = ElementTree()
tree.parse(in_path)
return tree
开发者ID:luoguoling,项目名称:homepython,代码行数:7,代码来源:xml2.py
注:本文中的xml.etree.ElementTree.ElementTree类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论