本文整理汇总了Python中xml.etree.ElementTree.SubElement.extend方法的典型用法代码示例。如果您正苦于以下问题:Python SubElement.extend方法的具体用法?Python SubElement.extend怎么用?Python SubElement.extend使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.etree.ElementTree.SubElement
的用法示例。
在下文中一共展示了SubElement.extend方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: createXml
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
def createXml():
top = Element("top")
comment = Comment("this is a xml test")
top.append(comment)
info = SubElement(top,"info") # add sub element
for i in range(4):
name = "name %d"%i
# set attribute, the third parameter is dictionary
people1 = SubElement(info,"people",
{"age":str(i),"name":name}
)
people1.text = "people%d" %(i) #set text
peopleElementList = [Element("people",{"age":str(i),"name":"name"+str(i)}) for i in range(5,9)]
for (index,ele) in enumerate(peopleElementList):
ele.text = "people%d" %(index+5)
#use extend to add element list
info.extend(peopleElementList)
#peopleEleList2 = XML('''<people age="0" name="name 0">people0</people><people age="1" name="name 1">people1</people><people age="2" name="name 2">people2</people>''')
#info.extend(peopleEleList2)
print prettify(top)
#Serializing XML to a Stream
ElementTree(top).write(sys.stdout)
#XML to a
ElementTree(top).write(sys.stdout)
示例2: mergeLogs
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
def mergeLogs(fromFilePath, toFilePath, outputFilePath):
utf8open = lambda s: open(s, 'r', 'utf8')
outputDoc = E('html')
with utf8open(fromFilePath) as fromFile, utf8open(toFilePath) as toFile:
# the body and HTML tags are left open so the app can just append
# when a new message comes in. we have to close them.
# note: this could also be taken care of by BeautifulSoup or
# perhaps lxml.html
fromDoc = fromstring(fromFile.read() + '</BODY></HTML>')
toDoc = fromstring(toFile.read() + '</BODY></HTML>')
# copy the head tag so formatting and stuff is preserved in our new doc
outputDoc.append(fromDoc.find('HEAD').copy())
fromMessages = fromDoc.findall('./BODY/div')
toMessages = toDoc.findall('./BODY/div')
allMessages = list(fromMessages) + list(toMessages)
allMessages.sort(key = lambda e: time.strptime(e.attrib['timestamp'], '%Y-%m-%d %H:%M:%S'))
body = SE(outputDoc, 'BODY', attrib = fromDoc.find('BODY').attrib)
body.extend(x.copy() for x in allMessages)
ElementTree(outputDoc).write(outputFilePath, 'utf8')
示例3: get_nodes
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
def get_nodes(node):
d = Element('page')
if (node != 'Root' and node != "0"):
filename = DIR + "/ImportXmls/" + node + '.xml'
doc = etree.parse(filename)
folder = SubElement(d, 'folder')
folder.text = doc.find('folder').text
url = SubElement(d, 'url')
url.text = doc.find('url').text
else:
folder = SubElement(d, 'folder')
folder.text = "nerokas XMLrakenne"
url = SubElement(d, 'url')
url.text = ''
emptyElements = "content title keywords description language classes creatorUser creationTime modifierUser modificationTime".split(" ")
for elName in emptyElements:
newEl = SubElement(d, elName)
newEl.text = ''
# optional:
children = get_children(node)
if children:
pages = SubElement(d, 'pages')
pages.extend( [get_nodes(child) for child in children] )
return d
示例4: service_validate
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
def service_validate(request, require_st=True):
response = Element('cas:serviceResponse',
attrib={'xmlns:cas': 'http://www.yale.edu/tp/cas'})
try:
st = validate_ticket(request, require_st)
auth_success = SubElement(response, 'cas:authenticationSuccess')
user = SubElement(auth_success, 'cas:user')
user.text = st.user.get_username()
if st.policy.allow_proxy:
pgt = ProxyGrantingTicket.objects.create_for_request(request)
if pgt:
pgt_iou = SubElement(auth_success, 'cas:proxyGrantingTicket')
pgt_iou.text = pgt.iou
if st.pgt:
proxies = SubElement(auth_success, 'cas:proxies')
current = st
while current.pgt:
proxy = SubElement(proxies, 'cas:proxy')
proxy.text = current.pgt.url
current = current.pgt.st
attributes = SubElement(auth_success, 'cas:attributes')
fields = (FieldPermission.objects.all() if st.policy.is_trusted
else st.policy.field_permissions.all())
for f in fields:
try:
attributes.extend(f.serializer.to_xml(st.user, f.field))
except AttributeError:
# TODO: Should it be ignored or should it cause INTERNAL_ERROR?
pass
if len(attributes) == 0:
auth_success.remove(attributes)
except Error as ex:
auth_failure = SubElement(response, 'cas:authenticationFailure',
attrib={'code': ex.code})
auth_failure.text = ex.msg
return XMLResponse(response)
示例5: graph2agm
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
def graph2agm(self, _graphs):
"""receive a graph in dictionary and convert to xml object
you should know that dic object has underbar prefix
"""
root = Element('GraphML')
root.set('version', '0.1')
header = SubElement(root,"Header",{"copyright":"hogehoge","description":"xt2gml"})
node_names={}
edge_names={}
graph_data = SubElement(root,"GraphData")
i_graph=1
for _graph in _graphs:
#vertexes for a graph
vertexes=[]
for _node in _graph["nodes"]:
vertex=Element("Vertex",{"vertexId":str(_node["id"]+1),"dimension":str(1)})
if _node.has_key("name"):
vertex_label=SubElement(vertex,"VertexLabel",{"field":"node_name","value":_node["name"]})
node_names[_node["name"]]=True
vertexes.append(vertex)
#edges for a graph
edges=[]
for _edge in _graph["edges"]:
edge=Element("Edge",{
"edgeId":str(_edge["id"]+1),
"dimension":str(1),
"bgnVertexId":str(_edge["source"]+1),
"endVertexId":str(_edge["target"]+1),
"edgeType":_edge["edge_type"]
})
#print _edge
if _edge.has_key("type"):
edge_label=SubElement(edge,"EdgeLabel",{"field":"edge_name","value":_edge["type"]})
edge_names[_edge["type"]]=True
edges.append(edge)
#edge_names[]
graph = SubElement(graph_data,"Graph",{"graphId":str(i_graph)})
i_graph=i_graph+1
graph.extend(vertexes)
graph.extend(edges)
#header
data_dictionary = SubElement(header,"DataDictionary",{"numberOfFields":str(2)})
node_name_field = SubElement(data_dictionary,"DataField",{"name":"node_name","optype":"categorical"})
node_name_keys=[]
for key in node_names:
node_name_keys.append(Element("Value",{"value":key}))
node_name_field.extend(node_name_keys)
edge_name_field = SubElement(data_dictionary,"DataField",{"name":"edge_name","optype":"categorical"})
SubElement(edge_name_field,"Value",{"value":"owned_member"})
return self.prettify(root)
示例6: Element
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
# ElementTree_extend_node.py
from xml.etree.ElementTree import Element, SubElement, tostring, XML)
from ElementTree_pretty import prettify
top = Element('top')
parent = SubElement(top, 'genitore')
children = XML(
'<root><figlio num="0" /><figlio num="1" />'
'<figlio num="2" /></root>'
)
parent.extend(children)
print(prettify(top))
示例7: Element
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
top = Element('top')
parent_a = SubElement(top, 'parent', id='A')
parent_b = SubElement(top, 'parent', id='B')
# Create children
children = XML(
'<root><child num="0" /><child num="1" />'
'<child num="2" /></root>'
)
# Set the id to the Python object id of the node
# to make duplicates easier to spot.
for c in children:
c.set('id', str(id(c)))
# Add to first parent
parent_a.extend(children)
print('A:')
print(prettify(top))
print()
# Copy nodes to second parent
parent_b.extend(children)
print('B:')
print(prettify(top))
print()
示例8: main
# 需要导入模块: from xml.etree.ElementTree import SubElement [as 别名]
# 或者: from xml.etree.ElementTree.SubElement import extend [as 别名]
#.........这里部分代码省略.........
# intialize aspect category of the sentence as []
aspect_cat_sent = {'food':[], 'service':[], 'ambience':[], 'price':[], 'anecdotes/miscellaneous':[]}
category_polarity = {} # for category polarity
#print each_sentence
if each_sentence == []:
child_aspect_terms.text = '\n\t\t'
child_aspect_cat= SubElement(child_aspect_cats, 'aspectCategory',
{'category':'anecdotes/miscellaneous',
'polarity':'neutral'})
#child_aspect_cats.text = '\n\t\t'
continue
for each_term in each_sentence:
for aspect, value in each_term.iteritems():
score = 0
aspect_terms = ''
# find the score of each aspect
if value != []:
for each_value in value:
aspect_terms = aspect_terms + each_value
sentiment = TextBlob(each_value).sentiment.polarity
score = score + sentiment
# find the category depending on the adjective
aspect_cat = detect_aspect_cat(each_value)
for each_cat in aspect_cat:
aspect_cat_sent[each_cat].append(score)
else:
aspect_cat = ['anecdotes/miscellaneous'] # if does not belong to any category
score = 0 # if no adjective for aspect => score=0
data['aspect_term'] = aspect
# find out the similarity depending on the aspct term and category
x = detect_similarity(aspect)
# print "xxxxxxxxxxxx",x
if x != None:
similar_category, similar_score = x[0], x[1]
#print similar_category, similar_score, aspect_cat_sent[similar_category], score
aspect_cat_sent[similar_category].append(score)
if score > 0:
data['polarity'] = "positive"
elif score < 0:
data['polarity'] = "negative"
else:
data['polarity'] = "neutral"
# detect polarity of category
# print aspect_cat_sent
for cat, score in aspect_cat_sent.iteritems():
if aspect_cat_sent[cat] != []:
# print aspect_cat_sent[cat]
total_score = sum(aspect_cat_sent[cat])
if total_score > 0:
category_polarity[cat] = 'positive'
elif total_score < 0:
category_polarity[cat] = 'negative'
else:
category_polarity[cat] = 'neutral'
# assign values 'from' and 'to'
# print "text:", data['text'], data['aspect_term']
try:
data['from'] = data['text'].index(data['aspect_term'])
data['to'] = data['from'] + len(data['aspect_term'])
except:
pass
child_aspect_term = SubElement(child_aspect_terms, 'aspectTerm',
{'term':data['aspect_term'],
'polarity':data['polarity'],
'from':str(data['from']),
'to':str(data['to']) }) #opens tag <aspectTerm>
child_aspect_terms.extend(child_aspect_term)
# print aspect_cat_sent
# print category_polarity
for key, value in category_polarity.iteritems():
child_aspect_cat= SubElement(child_aspect_cats, 'aspectCategory',
{'category':key,
'polarity':value })
child_aspect_cats.extend(child_aspect_cat)
#child_aspect_cat.text = '\n\t\t'
# prints the entire xml file
if (i == len(all_sentences)-1):
#print i
print prettify(top)