当前位置: 首页>>代码示例>>Python>>正文


Python etree.ElementTree方法代码示例

本文整理汇总了Python中lxml.etree.ElementTree方法的典型用法代码示例。如果您正苦于以下问题:Python etree.ElementTree方法的具体用法?Python etree.ElementTree怎么用?Python etree.ElementTree使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lxml.etree的用法示例。


在下文中一共展示了etree.ElementTree方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: mapSave

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def mapSave(regions,filename):
    """
    Saves a region map to an XML file
    """
    root = ET.Element('map')
    for name,table in regions.items():
        node = ET.SubElement(root,'region')
        node.set('name',name)
        if table.has_key('value'): node.set('value',str(table['value']))
        if table.has_key('occupants'): node.set('occupants',str(table['occupants']))
        node.set('owner',str(table['owner']))
        for neighbor in table['neighbors']:
            subnode = ET.SubElement(node,'neighbor')
            subnode.set('name',neighbor)
    tree = ET.ElementTree(root)
    tree.write(filename,pretty_print=True)
    return tree 
开发者ID:pynadath,项目名称:psychsim,代码行数:19,代码来源:teamofrivals.py

示例2: output2lex

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def output2lex(output,filename):
    lexicon_output = open(filename,"wb")
    lexicon = ET.Element("lexicon")
    tree = ET.ElementTree(lexicon)

    for list_item in output:
        lex_entry = ET.SubElement(lexicon,"lex")
        if list_item["pron"] is not None:
            lex_entry.attrib["ipa"]=list_item["pron"]
        if list_item["x-sampa"] is not None:
            lex_entry.attrib["x-sampa"]=list_item["x-sampa"]
        lex_entry.text=list_item["word"]

    tree.write(
            lexicon_output,pretty_print=True,   
            xml_declaration=True,encoding="utf-8") 
开发者ID:Idlak,项目名称:Living-Audio-Dataset,代码行数:18,代码来源:wiktionary2lex.py

示例3: create_output

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def create_output(phone_map,output_file,nuclei=[],add_nuclei=False):
    root = ET.Element("ipa_mapping")
    tree = ET.ElementTree(root)
    for ipa, phone in phone_map.items():
        mapping = ET.SubElement(root, "map")
        mapping.attrib["pron"] = phone
        mapping.attrib["ipa"] = ipa
        if add_nuclei:
            if phone in nuclei:
                mapping.attrib["nucleus"] = "true"
            else:
                mapping.attrib["nucleus"] = "false"
    mapping_output = open(output_file,"wb")
    tree.write(
            mapping_output,pretty_print=True,   
            xml_declaration=True,encoding="utf-8") 
开发者ID:Idlak,项目名称:Living-Audio-Dataset,代码行数:18,代码来源:phoneset2ipamap.py

示例4: main

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def main():
    """Use locals() to create a PyraTree, then get JSON/XML representations of the PyraTree data and print them."""
    # Put Arya-generated code here
    polUni = cobra.model.pol.Uni('')
    fvTenant = cobra.model.fv.Tenant(polUni, 'pod1')

    # Create the tree
    tree = PyraTree('polUni', locals())

    # Acquire a copy of the tree to use, e.g to save/modify/post.
    dict_tree = tree.dtree
    xml_tree = tree.etree
    json_tree = tree.jtree

    # Example output
    print(ElementTree.tostring(xml_tree, encoding='utf-8'))
    print(json.dumps(json_tree, indent=4, sort_keys=True)) 
开发者ID:datacenter,项目名称:arya,代码行数:19,代码来源:pyra.py

示例5: prep_schema_doc

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def prep_schema_doc(infile, outfile, inpath, options):
    doc1 = etree.parse(infile)
    root1 = doc1.getroot()
    params = Params()
    params.parent_url = infile
    params.base_url = os.path.split(inpath)[0]
    inserts = []
    if not options.no_collect_includes:
        collect_inserts(root1, params, inserts, options)
        root2 = copy.copy(root1)
        clear_includes_and_imports(root2)
        for insert_node in inserts:
            root2.append(insert_node)
    else:
        root2 = root1
    if not options.no_redefine_groups:
        process_groups(root2)
    raise_anon_complextypes(root2)
    fix_type_names(root2, options)
    doc2 = etree.ElementTree(root2)
    if sys.version_info.major == 2:
        doc2.write(outfile)
    else:
        outfile.write(etree.tostring(root2).decode('utf-8'))
    return doc2 
开发者ID:nyoka-pmml,项目名称:nyoka,代码行数:27,代码来源:process_includes.py

示例6: parse_instance

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def parse_instance(content, outdir):
    categories = {d['id']: d['name'] for d in content['categories']}
    # merge images and annotations: id in images vs image_id in annotations
    merged_info_list = list(map(cytoolz.merge, cytoolz.join('id', content['images'], 'image_id', content['annotations'])))
    # convert category id to name
    for instance in merged_info_list:
        instance['category_id'] = categories[instance['category_id']]
    # group by filename to pool all bbox in same file
    for name, groups in cytoolz.groupby('file_name', merged_info_list).items():
        anno_tree = instance2xml_base(groups[0])
        # if one file have multiple different objects, save it in each category sub-directory
        filenames = []
        for group in groups:
            filenames.append(os.path.join(outdir, re.sub(" ", "_", group['category_id']),
                                    os.path.splitext(name)[0] + ".xml"))
            anno_tree.append(instance2xml_bbox(group, bbox_type='xyxy'))
        for filename in filenames:
            etree.ElementTree(anno_tree).write(filename, pretty_print=True)
        print("Formating instance xml file {} done!".format(name)) 
开发者ID:CasiaFan,项目名称:Dataset_to_VOC_converter,代码行数:21,代码来源:anno_coco2voc.py

示例7: parse_keypoints

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def parse_keypoints(content, outdir):
    keypoints = dict(zip(range(1, len(content['categories'][0]['keypoints'])+1), content['categories'][0]['keypoints']))
    # merge images and annotations: id in images vs image_id in annotations
    merged_info_list = map(cytoolz.merge, cytoolz.join('id', content['images'], 'image_id', content['annotations']))
    # convert category name to person
    for keypoint in merged_info_list:
        keypoint['category_id'] = "person"
    # group by filename to pool all bbox and keypoint in same file
    for name, groups in cytoolz.groupby('file_name', merged_info_list).items():
        filename = os.path.join(outdir, os.path.splitext(name)[0]+".xml")
        anno_tree = keypoints2xml_base(groups[0])
        for group in groups:
            anno_tree = keypoints2xml_object(group, anno_tree, keypoints, bbox_type="xyxy")
        doc = etree.ElementTree(anno_tree)
        doc.write(open(filename, "w"), pretty_print=True)
        print("Formating keypoints xml file {} done!".format(name)) 
开发者ID:CasiaFan,项目名称:Dataset_to_VOC_converter,代码行数:18,代码来源:anno_coco2voc.py

示例8: parse_anno_file

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def parse_anno_file(inputdir, outputdir):
    # annotation sub-directories in hda annotation input directory
    assert os.path.exists(inputdir)
    sub_dirs = os.listdir(inputdir)
    for sub_dir in sub_dirs:
        print("Parsing annotations of camera: ", sub_dir)
        anno_file = os.path.join(inputdir, sub_dir, "Detections/allD.txt")
        annos = anno_file2dict(anno_file)
        outdir = os.path.join(outputdir, "Annotations", sub_dir)
        if not os.path.exists(outdir):
            os.makedirs(outdir)
        for filename, anno in annos.items():
            anno_tree = instance2xml_base(anno)
            outfile = os.path.join(outdir, os.path.splitext(filename)[0]+".xml")
            print("Generating annotation xml file of picture: ", filename)
            etree.ElementTree(anno_tree).write(outfile, pretty_print=True) 
开发者ID:CasiaFan,项目名称:Dataset_to_VOC_converter,代码行数:18,代码来源:anno_hda2voc.py

示例9: readXml

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def readXml(self, simType):
        path = os.path.dirname(__file__)
        if simType == types.TYPE_USIM:
            path = os.path.join(path, "sim_files_3g.xml")
        else:
            path = os.path.join(path, "sim_files_2g.xml")
        tree = etree.ElementTree()
        if not os.path.exists(path):
            logging.warning("File %s not exists" %path)
            logging.info("Create xml")
            if simType == types.TYPE_USIM:
                root = etree.Element('sim_3G')
            else:
                root = etree.Element('sim_2G')
        else:
            parser = etree.XMLParser(remove_blank_text=True)
            root = etree.parse(path, parser).getroot()
        return path, root 
开发者ID:kamwar,项目名称:simLAB,代码行数:20,代码来源:sim_files.py

示例10: getPathFromFile

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def getPathFromFile(self, file):
        if file == None:
            return
        pathXml = etree.ElementTree(self.root).getpath(file)
        pathXml = pathXml.split("mf")[1]
        path = "./mf[@id='3F00']"
        for _file in pathXml.split('/'):
            if not _file:
                #path = types.addToPath(path, "/")
                continue
            absPath = types.addToPath(path, _file)
            id = etree.ElementTree(self.root).xpath(absPath)[0].attrib['id']
            #"./mf/df[@id='ADF0']"
            fileId = "%s[@id='%s']" %(_file.split('[')[0], id)
            path = types.addToPath(path, fileId)
        return path 
开发者ID:kamwar,项目名称:simLAB,代码行数:18,代码来源:sim_xml.py

示例11: write

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def write(dictionary, args, output_file_path):
    try:
        print_debug("Creating XML tree...", args.debug)
        dictionary_elem = etree.Element("dictionary")
        for index in dictionary.entries_index_sorted:
            entry = dictionary.entries[index]
            entry_elem = etree.SubElement(dictionary_elem, "entry")
            key_elem = etree.SubElement(entry_elem, "key")
            key_elem.text = entry.headword
            def_elem = etree.SubElement(entry_elem, "def")
            def_elem.text = entry.definition
        tree = etree.ElementTree(dictionary_elem)
        print_debug("Creating XML tree... done", args.debug)
        print_debug("Writing to file '%s'..." % (output_file_path), args.debug)
        tree.write(
            output_file_path,
            pretty_print=True,
            xml_declaration=True
        )
        print_debug("Writing to file '%s'... success" % (output_file_path), args.debug)
        return [output_file_path]
    except:
        print_error("Writing to file '%s'... failure" % (output_file_path))
        return None 
开发者ID:pettarin,项目名称:penelope,代码行数:26,代码来源:format_xml.py

示例12: _g_process_et_items

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def _g_process_et_items(path, tag) -> Iterable[Tuple]:
        """
        Generator: Processes ElementTree items in a memory
        efficient way
        """

        context: etree.ElementTree = etree.iterparse(
            path, events=('end',), tag=tag
        )

        for event, elem in context:
            yield event, elem

            # delete content of node once we're done processing
            # it. If we don't then it would stay in memory
            elem.clear() 
开发者ID:Wikidata,项目名称:soweego,代码行数:18,代码来源:discogs_dump_extractor.py

示例13: __init__

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def __init__(self, *a, **k):
        # Importing names from *a and **k or using defaults
        self.ffpath = k.setdefault('ffpath', None)
        self.root   = k.setdefault('root', None) if 'tree' not in k else k['tree'].getroot()

        if len(a) > 0:
            etype   = type(et.Element("a"))
            ettype  = type(et.ElementTree())
            for s in a:
                if isinstance(s, (etype,ettype)):
                    if self.root == None:
                        self.root = s.getroot() if isinstance(s,ettype) else s
                elif isinstance(s, str):
                    if self.ffpath == None:
                        self.ffpath = s
                else:
                    raise ValueError("XML\'s initializer only accepts string, ElementTree or Element")
        
        if self.ffpath != None and self.root == None:
            try:
                self.root = et.parse(self.ffpath).getroot()
            except (IOError, et.ParseError):
                # TODO Populate tree and save it
                raise 
开发者ID:ActiveState,项目名称:code,代码行数:26,代码来源:recipe-578492.py

示例14: CrawData

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def CrawData(self, url):

        if   self.Login !="" and  self.haslogin == False:
            self.HttpItem.opener = self.autologin(self.Login);
            self.haslogin = True;
        html = self.HttpItem.GetHTML(url);

        root =None if html=='' else etree.HTML(html);
        if root is None:
            return {} if self.IsMultiData == 'One' else [];

        tree = etree.ElementTree(root);
        if isinstance(self.CrawItems, list) and len(self.CrawItems) == 0:
            return {'Content': html};

        return self.GetDataFromCrawItems(tree ); 
开发者ID:ferventdesert,项目名称:etlpy,代码行数:18,代码来源:spider.py

示例15: sortFile

# 需要导入模块: from lxml import etree [as 别名]
# 或者: from lxml.etree import ElementTree [as 别名]
def sortFile(fileobj):
    with open(fileobj['filename'], 'r') as original:
        # parse the XML file and get a pointer to the top
        xmldoc = le.parse(original)
        xmlroot = xmldoc.getroot()

        # create a new XML element that will be the top of
        #  the sorted copy of the XML file
        newxmlroot = le.Element(xmlroot.tag)

        # create the sorted copy of the XML file
        sortAttrs(xmlroot, newxmlroot)
        sortElements(list(xmlroot), newxmlroot)

        # write the sorted XML file to the temp file
        newtree = le.ElementTree(newxmlroot)
        with open(fileobj['tmpfilename'], 'wb') as newfile:
            newtree.write(newfile, pretty_print=True)


#
# sort each of the specified files 
开发者ID:ros-naoqi,项目名称:naoqi_bridge,代码行数:24,代码来源:xmldiff.py


注:本文中的lxml.etree.ElementTree方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。