本文整理汇总了Python中xml.etree.cElementTree.ElementTree.find方法的典型用法代码示例。如果您正苦于以下问题:Python ElementTree.find方法的具体用法?Python ElementTree.find怎么用?Python ElementTree.find使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.cElementTree.ElementTree
的用法示例。
在下文中一共展示了ElementTree.find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_article_contrib_authors
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def _get_article_contrib_authors(tree):
from sys import stderr
"""
Given an ElementTree, returns article authors in a format suitable for citation.
"""
authors = []
front = ElementTree(tree).find('front')
for contrib in front.iter('contrib'):
contribTree = ElementTree(contrib)
try:
surname = contribTree.find('name/surname').text
except AttributeError: # author is not a natural person
try:
citation_name = contribTree.find('collab').text
if citation_name is not None:
authors.append(citation_name)
continue
except AttributeError: # name has no immediate text node
continue
try:
given_names = contribTree.find('name/given-names').text
citation_name = ' '.join([surname, given_names[0]])
except AttributeError: # no given names
citation_name = surname
except TypeError: # also no given names
citation_name = surname
if citation_name is not None:
authors.append(citation_name)
return ', '.join(authors)
示例2: load
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def load(cls, filename):
project_root = ElementTree().parse(filename)
settings_node = project_root.find(cls.__PROJECT_SETTINGS_NODE_NAME)
tracks_node = project_root.find(cls.__PROJECT_TRACKS_NODE_NAME)
track_nodes = tracks_node.findall(cls.__PROJECT_TRACK_NODE_NAME)
for node in track_nodes:
print node
示例3: _get_supplementary_material
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def _get_supplementary_material(tree, rid):
"""
Given an ElementTree and an rid, returns supplementary material as a dictionary
containing url, mimetype and label and caption.
"""
for sup in tree.iter('supplementary-material'):
try:
if sup.attrib['id'] == rid: # supplementary material found
result = {}
sup_tree = ElementTree(sup)
label = sup_tree.find('label')
result['label'] = ''
if label is not None:
result['label'] = label.text
caption = sup_tree.find('caption')
result['caption'] = ''
if caption is not None:
result['caption'] = ' '.join(caption.itertext())
media = sup_tree.find('media')
if media is not None:
result['mimetype'] = media.attrib['mimetype']
result['mime-subtype'] = media.attrib['mime-subtype']
result['url'] = _get_supplementary_material_url(
_get_pmcid(tree),
media.attrib['{http://www.w3.org/1999/xlink}href']
)
return result
except KeyError: # supplementary material has no ID
continue
示例4: __init__
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def __init__(self,
protocol = None,
host_name = None,
user_name = None,
password = None,
database_configuration = None,
test = False,
database_server_configuration_file_path = None,
sqlite_db_path = None):
if database_server_configuration_file_path is None:
database_server_configuration_file_path = os.path.join(os.environ['OPUS_HOME'], 'settings', 'database_server_configurations.xml')
if (protocol is None or test) and host_name is None and user_name is None and password is None:
if not os.path.exists(database_server_configuration_file_path):
raise Exception('You do not have a file %s storing information about your database server configurations. Cannot load database.'%database_server_configuration_file_path)
if database_configuration is None:
db_node = self._database_configuration_node()
else:
db_node = database_configuration
database_configuration = ElementTree(file = database_server_configuration_file_path).getroot().find(db_node)
if database_configuration is None:
raise Exception('Could not find an entry in %s for %s. Cannot load database.'%(database_server_configuration_file_path, db_node))
self.protocol = database_configuration.find('protocol').text
self.host_name = database_configuration.find('host_name').text
self.user_name = database_configuration.find('user_name').text
self.password = database_configuration.find('password').text
else:
if protocol is None:
self.protocol = get_default_database_engine()
else:
self.protocol = protocol.lower()
if host_name is None:
self.host_name = 'localhost'
else:
self.host_name = host_name
if user_name is None:
self.user_name = ''
else:
self.user_name = user_name
if password is None:
self.password = ''
else:
self.password = password
# If the password is the empty string or None, check if it is defined in the environment variable
# SQLPASSWORD - if so, use that.
if (self.password is None or self.password=='') and 'SQLPASSWORD' in os.environ:
self.password = os.environ['SQLPASSWORD']
self.sqlite_db_path = sqlite_db_path
示例5: _getresponse
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def _getresponse(self):
r = self.h.getresponse()
if r.status == 200:
et = ElementTree()
et.parse(r)
if et.find('status').text == 'OK':
return et
raise NessusException(et.find('contents').text)
elif r.status == 403:
self.token = None
raise NessusSessionException('Session timed out.')
raise NessusException(r.read())
示例6: main
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def main():
super_concat = False
options, args = interface()
xml = ElementTree().parse(options.input, parser=XMLParser(target=MyTreeBuilder()))
# delete the older subs. models from the xml file
for node in ["HKYModel", "gtrModel", "siteModel", "patterns", "treeLikelihood"]:
xml = delete_node(xml, node, 1)
# delete the kappa and frequency parameters in 'operators'
delete = ["kappa", "frequencies", "alpha", "pInv", "ac", "ag", "at", "cg", "gt"]
xml = delete_children_from_node(xml, xml.find("operators"), delete)
xml = delete_children_from_node(xml, xml.find("mcmc").find("posterior").find("prior"), delete)
# there are 2 log tags, disambiguated w/ id params. delete elements from
# the one we want (fileLog)
xml = delete_children_from_node(xml, get_file_log_section(xml), delete)
# jettison some comments
xml = comment_remover(
xml,
[
"The general time reversible",
"HKY substitution model",
"site model",
"The unique patterns from 1 to end",
"npatterns=",
],
)
# load our substitution model information
substitution_models = cPickle.load(open(options.subs))
snippets = ElementTree().parse(options.params, parser=XMLParser(target=MyTreeBuilder()))
# insert patterns on a per locus basis
insert_position = get_position(xml, "alignment")
xml = insert_patterns_for_locus(xml, substitution_models, insert_position, snippets)
# insert substitution models on a per locus basis
insert_position = get_position(xml, "strictClockBranchRates")
xml, insert_position = insert_models_for_locus(xml, substitution_models, insert_position, snippets)
# insert site models on a per locus basis
xml, insert_position = insert_site_models_for_locus(xml, substitution_models, insert_position, snippets)
# insert tree likelihoods on a per locus basis
xml, insert_position = insert_tree_likelihoods_for_locus(xml, substitution_models, insert_position, snippets)
# insert operators
xml = insert_operators_for_locus(xml, substitution_models, snippets)
write(xml, options.output)
pdb.set_trace()
"""model_names, site_names = get_xml_model_names(set(sub_models_from_modeltest.values()))
示例7: load
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def load(self):
"Nacteni ze souboru."
root = ElementTree(file=self.filename)
ret = self.Result()
size = int(root.find('world/cells').text)
ret.world = [[None for j in range(size)] for i in range(size)]
ret.species = int(root.find('world/species').text)
ret.iterations = int(root.find('world/iterations').text)
for organism in root.find('organisms'):
ret.world[int(organism.find('x_pos').text)][int(organism.find('y_pos').text)] = organism.find('species').text
return ret
示例8: extract_pos
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def extract_pos(link):
root_namespace_reg = re.compile("\{.*\}", re.IGNORECASE)
root_namespace = None
try:
data = urllib.urlopen(link)
tree = ElementTree()
parser = XMLParser(encoding="iso-8859-1")
tree.parse(data, parser=parser)
root_namespace = root_namespace_reg.findall(tree.getroot().tag)[0]
name = tree.find(".//{0}Document//{0}name".format(root_namespace)).text
# parse important datas
unparsed = tree.find(".//{0}Document//{0}Placemark//{0}description".format(root_namespace)).text
except Exception, e:
return
示例9: fulltext_search
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def fulltext_search(self, query, rows=None, start=None):
"""Does an advanced search on fulltext:blah.
You get back a pair (x,y) where x is the total # of hits
and y is a list of identifiers like ["foo", "bar", etc.]"""
query = self._prefix_query('fulltext', query)
result_list = self.raw_search(query, rows=rows, start=start)
e = ElementTree()
try:
e.parse(StringIO(result_list))
except SyntaxError as e:
raise SolrError(e)
total_nbr_text = e.find('info/range_info/total_nbr').text
# total_nbr_text = e.find('result').get('numFound') # for raw xml
total_nbr = int(total_nbr_text) if total_nbr_text else 0
out = []
for r in e.getiterator('hit'):
for d in r.find('metadata'):
for x in list(d.getiterator()):
if x.tag == "identifier":
xid = six.text_type(x.text).encode('utf-8')
if xid.startswith('OCA/'):
xid = xid[4:]
elif xid.endswith('.txt'):
xid = xid.split('/')[-1].split('_')[0]
elif xid.endswith('_ZZ'):
xid = xid[:-3]
out.append(xid)
break
return (total_nbr, out)
示例10: loadLanguageFile
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def loadLanguageFile(langfile):
""" Loads one or more languages from disk
Returns list of language codes found."""
global languagenames, languages
tree = ElementTree(file=langfile)
foundlangs = []
langslist = tree.find("wurmlanguages")
langs = langslist.findall("languagedef")
for language in langs:
code = language.attrib["code"]
name = language.attrib.get("name", code)
languagenames[code] = name
languages.setdefault(code, {}) # make sure the base map is ready
if code not in foundlangs:
foundlangs.append(code)
lstrings = language.findall("string")
for lstr in lstrings:
orig = _parse(lstr.find("original").text.strip())
tran = _parse(lstr.find("translation").text.strip())
languages[code][orig] = tran
return foundlangs
示例11: extractElement
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def extractElement(self, elementpath, respdata):
try:
tree = ElementTree()
tree.parse(StringIO(respdata))
except:
return None
# Strip off the top-level item
if elementpath[0] == '/':
elementpath = elementpath[1:]
splits = elementpath.split('/', 1)
root = splits[0]
if tree.getroot().tag != root:
return None
elif len(splits) == 1:
return tree.getroot().text
else:
elementpath = splits[1]
e = tree.find(elementpath)
if e is not None:
return e.text
else:
return None
示例12: search
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def search(query):
query = query.lower()
parsed = expr.parseString(query)[0]
res = parsed()
print
print("Searching for \"{}\"".format(query))
if res[1]:
print("Found {} results".format(len(res[0])))
for file_id in list(res[0])[:5]:
print(files[file_id])
words = parsed.words()
tree = ElementTree()
tree.parse(files[file_id])
body = tree.find('text').find('body')
for p in body:
words_copy = list(words)
at_least_one = False
for word in words_copy:
if word in word_reg_exp.findall(p.text.lower().encode('utf-8')):
at_least_one = True
words.remove(word)
if at_least_one:
print("----| {}".format(p.text.encode('utf-8')))
print
else:
print("Negative requests are not allowed")
print
示例13: _getBugInfo
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def _getBugInfo(self, bugno):
def _formatEmail(e):
if e.get('name'):
return '%s <%s>' % (self._encode(e.get('name')), e.text)
return e.text
bugXML = utils.web.getUrlFd(self.bugzillaRoot +
'show_bug.cgi?ctype=xml&excludefield=attachmentdata&'
'excludefield=long_desc&excludefield=attachment&id=' +
str(bugno))
etree = ElementTree(file=bugXML)
bugRoot = etree.find('bug')
buginfo = {
'bug_id': bugRoot.find('bug_id').text,
'summary': self._encode(bugRoot.find('short_desc').text),
'creation_time': bugRoot.find('creation_ts').text,
'last_change_time': bugRoot.find('delta_ts').text,
'bug_severity': bugRoot.find('bug_severity').text,
'bug_status': bugRoot.find('bug_status').text,
'resolution': ' ' + bugRoot.find('resolution').text
if bugRoot.find('resolution') != None
else '',
'product': self._encode(bugRoot.find('product').text),
'component': bugRoot.find('component').text,
'reporter': _formatEmail(bugRoot.find('reporter')),
'assigned_to': _formatEmail(bugRoot.find('assigned_to')),
'url': self.bugzillaRoot + str(bugno),
}
bugXML.close()
return buginfo
示例14: get_categories_from_pmid
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def get_categories_from_pmid(pmid):
"""
Gets MeSH headings, returns those not deemed too broad.
"""
if not type(pmid) == int:
raise TypeError, "Cannot get Categories for PMID %s of type %s." % (pmid, type(pmid))
url = 'http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&id=%s&retmode=xml' % pmid
xml_file = _get_file_from_url(url)
tree = ElementTree()
tree.parse(xml_file)
categories = []
for heading in tree.iterfind('PubmedArticle/MedlineCitation/MeshHeadingList/MeshHeading'):
htree = ElementTree(heading)
descriptor_text = htree.find('DescriptorName').text
if (htree.find('QualifierName') is not None) or \
(' ' in descriptor_text and not 'and' in descriptor_text):
categories.append(descriptor_text)
return categories
示例15: set_game_info
# 需要导入模块: from xml.etree.cElementTree import ElementTree [as 别名]
# 或者: from xml.etree.cElementTree.ElementTree import find [as 别名]
def set_game_info(self, info):
self.info = info
tree = ElementTree()
tree.parse(info["path"])
link_node = tree.find("link")
if link_node is not None:
self.link_field.set_text(link_node.text.strip())
else:
self.link_field.set_text("")