本文整理汇总了Python中xml.dom.minidom.Document.createComment方法的典型用法代码示例。如果您正苦于以下问题:Python Document.createComment方法的具体用法?Python Document.createComment怎么用?Python Document.createComment使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xml.dom.minidom.Document
的用法示例。
在下文中一共展示了Document.createComment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: formXml
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def formXml(self):
"""Form the XML to be written to RssFeeds.xml"""
#create the document
doc = Document()
#create root element
rssfeedsTag = doc.createElement('rssfeeds')
doc.appendChild(rssfeedsTag)
#create comments
c1Tag = doc.createComment('RSS feeds. To have multiple feeds, just add a feed to the set. You can also have multiple sets.')
c2Tag = doc.createComment('To use different sets in your skin, each must be called from skin with a unique id.')
rssfeedsTag.appendChild(c1Tag)
rssfeedsTag.appendChild(c2Tag)
for setNum in sorted(self.feedsList.keys()):
#create sets
setTag = doc.createElement('set')
#create attributes
setTag.setAttribute('id', self.feedsList[setNum]['attrs']['id'])
#only write rtl tags if they've been explicitly set
if 'rtl' in self.feedsList[setNum]['attrs']:
setTag.setAttribute('rtl', self.feedsList[setNum]['attrs']['rtl'])
rssfeedsTag.appendChild(setTag)
#create feed elements
for feed in self.feedsList[setNum]['feedslist']:
feedTag = doc.createElement('feed')
feedTag.setAttribute('updateinterval', feed['updateinterval'])
feedUrl = doc.createTextNode(feed['url'])
feedTag.appendChild(feedUrl)
setTag.appendChild(feedTag)
return doc.toprettyxml(indent = ' ', encoding = 'UTF-8')
示例2: _replace_loop_placeholder
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def _replace_loop_placeholder(paragraph: Element, placeholder_text: str):
"""Replace paragraph containing mustache loop
:param paragraph:
:param placeholder_text:
"""
parent_node = paragraph.parentNode
if parent_node.tagName == 'w:body':
# If placeholder is within body replace paragraph with xml comment
# containing mustache loop
comment = Document.createComment(parent_node, placeholder_text)
parent_node.replaceChild(comment, paragraph)
elif parent_node.tagName == 'w:tc':
# If placeholder is within a table, replace row it resides with xml
# comment containing mustache loop
row = parent_node.parentNode
table = row.parentNode
comment = Document.createComment(table, placeholder_text)
table.replaceChild(comment, row)
示例3: convert_file
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def convert_file(playlist):
'''
Playlist parser
'''
channel_count = 0
EOL = '\n'
header = playlist.readline()
# Catching an exeption if the 1-st string in a *nix-formatted .m3u is empty
try:
if header[-2] == '\r':
EOL = '\r' + EOL # Windows EOL convention
except IndexError: pass
if '#EXTM3U' in header:
xml_config = Document()
comment = xml_config.createComment(' This file is created by m3u2xml convertor ')
xml_config.appendChild(comment)
demo = xml_config.createElement('demo')
xml_config.appendChild(demo)
channels = xml_config.createElement('channels')
demo.appendChild(channels)
groups = xml_config.createElement('groups')
demo.appendChild(groups)
channel_info = []
groups_list = {}
# Extra protocols can be added if necessary
PROTOCOLS = ['udp', 'http', 'rtmpe', 'rtp', 'rtsp']
try:
start_number = int(_START_No)
except ValueError:
start_number = 1
for line in playlist:
if line.split(':')[0] == '#EXTINF':
channel_info.append(line.split(',')[-1].replace(EOL, '').decode(_ENC))
if 'group-title=' in line and _ADDON.getSetting('groups') == 'true':
current_group = re.search(
r'group-title=".*?"', line).group().replace('group-title=', '').replace('\"', '').decode(_ENC)
groups_list[current_group] = []
elif line.split(':')[0] in PROTOCOLS:
if _ADDON.getSetting('useproxy') == 'true':
channel_info.append(_PROXY + line.replace(EOL, '').replace(':/', '').replace('@', ''))
else:
channel_info.append(line.replace(EOL, ''))
channel_num = start_number + channel_count
chan_rec_create(xml_config, channels, channel_info, channel_num)
if groups_list:
groups_list[current_group].append(channel_num)
channel_count += 1
channel_info = []
if groups_list:
groups_create(xml_config, demo, groups_list)
out_xml = codecs.open(_PVR_CONFIG, encoding='utf-8', mode='w')
xml_config.writexml(out_xml, newl='\n')
out_xml.close()
playlist.close()
return channel_count
示例4: write_student_to_xml
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def write_student_to_xml(dic=None, to_path=None):
if dic is None or to_path is None:
return None
doc = Document()
root_node = doc.createElement("root")
doc.appendChild(root_node)
stu_node = doc.createElement("students")
root_node.appendChild(stu_node)
note_node = doc.createComment("\n\t学生信息表\n\t\"id\" : [名字, 数学, 语文, 英文]\n\t")
stu_node.appendChild(note_node)
# data = json.dumps(dic, ensure_ascii=False, indent=1)
dic_node = doc.createTextNode(stringer.dict_to_json(dic, "\t\t"))
stu_node.appendChild(dic_node)
file = open(to_path, "w")
file.write(doc.toprettyxml())
# doc.writexml(file,' ',' ','\n','utf-8')
file.close()
示例5: getXMLFile
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def getXMLFile(self):
self.traversalFileFolder(self.sourcedir)
doc = Document()
doc.appendChild(doc.createComment("Simple xml document__chapter 8"))
data_storage = doc.createElement("data_storage")
doc.appendChild(data_storage)
source = doc.createElement("source")
data_storage.appendChild(source)
source_data = doc.createTextNode(self.sourcedir[self.sourcedir.index("/") + 1 :])
source.appendChild(source_data)
classtype = doc.createElement("classtype")
data_storage.appendChild(classtype)
listlabel = list(self.filedict.keys())
listlabel.sort()
for key in listlabel:
classlabel = doc.createElement(key)
classtype.appendChild(classlabel)
label = doc.createElement("label")
label_text = doc.createTextNode(str(listlabel.index(key)))
label.appendChild(label_text)
classlabel.appendChild(label)
values = self.filedict[key]
for value in values:
li = doc.createElement("li")
li_text = doc.createTextNode(value)
li.appendChild(li_text)
classlabel.appendChild(li)
file_object = open(self.outfile, "w")
file_object.write(doc.toprettyxml())
file_object.close()
示例6: create_xml
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def create_xml(self, display_time, transition_time = 5):
xmldoc = Document()
background = xmldoc.createElement('background')
comment = xmldoc.createComment("Created by BAckground Xml Creater\n [https://github.com/abilng/gnome-baxc]")
xmldoc.appendChild(comment)
xmldoc.appendChild(background)
starttime = xmldoc.createElement('starttime')
sTime = datetime.datetime.now()
year = xmldoc.createElement('year')
year.appendChild(xmldoc.createTextNode('%s' % sTime.year))
starttime.appendChild(year)
month = xmldoc.createElement('month')
month.appendChild(xmldoc.createTextNode('%s' % sTime.month))
starttime.appendChild(month)
day = xmldoc.createElement('day')
day.appendChild(xmldoc.createTextNode('%s' % sTime.day))
starttime.appendChild(day)
hour = xmldoc.createElement('hour')
hour.appendChild(xmldoc.createTextNode('%s' % sTime.hour))
starttime.appendChild(hour)
minute = xmldoc.createElement('minute')
minute.appendChild(xmldoc.createTextNode('%s' % sTime.minute))
starttime.appendChild(minute)
second = xmldoc.createElement('second')
second.appendChild(xmldoc.createTextNode('%s' % sTime.second))
starttime.appendChild(second)
background.appendChild(starttime)
for i in range(len(self.images)):
currentImage = self.images[i]
try:
next = self.images[i + 1]
except IndexError:
next = self.images[0]
static = xmldoc.createElement('static')
duration = xmldoc.createElement('duration')
duration.appendChild(xmldoc.createTextNode("%s.0" % display_time))
static.appendChild(duration)
file = xmldoc.createElement('file')
file.appendChild(xmldoc.createTextNode(str(currentImage)))
static.appendChild(file)
background.appendChild(static)
transition = xmldoc.createElement('transition')
duration = xmldoc.createElement('duration')
duration.appendChild(xmldoc.createTextNode("%s.0" % transition_time))
transition.appendChild(duration)
transitionFrom = xmldoc.createElement('from')
transitionFrom.appendChild(xmldoc.createTextNode(str(currentImage)))
transition.appendChild(transitionFrom)
transitionTo = xmldoc.createElement('transitionTo')
transitionTo.appendChild(xmldoc.createTextNode(str(next)))
transition.appendChild(transitionTo)
background.appendChild(transition)
return xmldoc.toxml()
示例7: generation_Pserver
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def generation_Pserver(directory):
"""
generate the package 'test' for the Package Server tests
"""
makedirs ("%s/test" %(directory))#create the directory of the test's package
doc=Document()
comment = doc.createComment("DOCTYPE package SYSTEM \"package_v1.dtd\"")
doc.appendChild(comment)
package = doc.createElement("package")
package.setAttribute("id","test")
doc.appendChild(package)
name = doc.createElement("name")
package.appendChild(name)
natext = doc.createTextNode("TestPackage")
name.appendChild(natext)
version = doc.createElement("version")
package.appendChild(version)
numeric = doc.createElement("numeric")
version.appendChild(numeric)
nutext = doc.createTextNode("")
numeric.appendChild(nutext)
label = doc.createElement("label")
version.appendChild(label)
latext = doc.createTextNode("2.0.0.9")
label.appendChild(latext)
description = doc.createElement("description")
package.appendChild(description)
dtext = doc.createTextNode("Ceci est le package de test")
description.appendChild(dtext)
commands = doc.createElement("commands")
commands.setAttribute("reboot","1")
package.appendChild(commands)
Precommands = doc.createElement("Precommands")
commands.appendChild(Precommands)
Ptext = doc.createTextNode("")
Precommands.appendChild(Ptext)
installInit = doc.createElement("installInit")
commands.appendChild(installInit)
itext = doc.createTextNode("")
installInit.appendChild(itext)
command = doc.createElement("command")
command.setAttribute("name","commande")
commands.appendChild(command)
ctext = doc.createTextNode("./install.bat")
command.appendChild(ctext)
postCommandSuccess = doc.createElement("postCommandSuccess")
commands.appendChild(postCommandSuccess)
Stext = doc.createTextNode("")
postCommandSuccess.appendChild(Stext)
postCommandFailure = doc.createElement("postCommandFailure")
commands.appendChild(postCommandFailure)
Ftext = doc.createTextNode("")
postCommandFailure.appendChild(Ftext)
fichier=open("%s/test/conf.xml" %(directory),"w")
doc.writexml(fichier,indent=" ",addindent=" ",newl="\n", encoding="utf-8")
chdir("%s/test" %(directory))
instalfile=open("install.bat","w")
instalfile.write("I can\'t be installed")
instalfile.close()
示例8: extract
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
# resolution of the actual extractor class based on the tool command line argument.
options.extractor_class = options.available_extractors[options.tool]
except KeyError:
parser.error('Tool "%s" not found. Available tools are: %s' %
(options.tool, ', '.join(options.available_extractors.keys())))
# instanciation of the actual extractor
extractor = options.extractor_class()
try:
# the extract() method should return a list of Rule objects
rules = extractor.extract(*args) or []
except ExtractorArgumentError, err:
# extractors can raise OptionError if the arguments are inconsistent
parser.error(err)
# XML document construction
doc = Document()
doc.appendChild(doc.createComment('EXTRACTED "%s" RULES FOR SONAR' % options.tool))
rules_elt = doc.createElement('rules')
for rule in rules:
rules_elt.appendChild(rule.to_xml_element())
doc.appendChild(rules_elt)
# write to standard output
if options.format:
doc.writexml(sys.stdout, addindent=' ', newl='\n', encoding='utf-8')
else:
doc.writexml(sys.stdout, encoding='utf-8')
sys.stdout.write('\n')
示例9: open
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
rowIndex = 0
id = 0
fExe = open(workPath + "//cmd", "w")
for row in reader:
if rowIndex == 0:
header = row # .split(',')
N = size(header)
else:
cols = row # .split(',')
if verbose:
print cols[0]
# Create the minidom document
doc = Document()
cc1 = doc.createComment("license:")
cc2 = doc.createComment("strictly confidential. Propietary Information")
doc.appendChild(cc1)
doc.appendChild(cc2)
# Create the <main> base element
top = doc.createElement("dvg_sns")
doc.appendChild(top)
top.setAttribute("id", str(id))
top.setIdAttribute("id")
id = id + 1
top.setAttribute("testName", cols[0])
if individualTestDir == True:
workPathTemp = workPath + cols[0]
shutil.rmtree(workPathTemp, True)
os.mkdir(workPathTemp)
else:
示例10: Document
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
# Initialize types
xmldoc = Document()
# in case we don't have a key line (bad!), assume some default field indices
index_feature_name = 0
index_target = 1
index_diameter = 2
index_lat = 3
index_long = 4
# 5 is not used yet
index_feature_type = 6
# 7 is not used yet
index_approval = 8
index_origin = 9
# Add introductory comments
introcomment1 = xmldoc.createComment("Landmark coordinates from USGS Astrogeology Research Program")
introcomment2 = xmldoc.createComment("http://planetarynames.wr.usgs.gov/AdvancedSearch")
introcomment3 = xmldoc.createComment("Landmarks to be displayed in the user interface. ")
xmldoc.appendChild(introcomment1)
xmldoc.appendChild(introcomment2)
xmldoc.appendChild(introcomment3)
# Create the base XML element
landmarks = xmldoc.createElement("landmark-list")
#landmarks.setAttribute("xmlns", "http://mars-sim.sourceforge.net/landmarks")
#landmarks.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
#landmarks.setAttribute("xsi:schemaLocation", "http://mars-sim.sourceforge.net/landmarks schema/landmarks.xsd")
xmldoc.appendChild(landmarks)
# Open and parse the search results file (TSV), get the data key and data
示例11: save
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def save(self, outfile):
"""
Save the current working SPN to a file of a given name
in the current dir. vdict contains the labels and data
of the vector vars, mdict is the matrices.
"""
import re
import datetime
from xml.dom.minidom import Document
# Open file, build header
f = open(outfile, 'w')
doc = Document()
# write header with program, date/time:
comm = doc.createComment('Created by SPNlib on %s' \
% str(datetime.datetime.now().strftime("%d-%m-%Y at %H:%M")))
doc.appendChild(comm)
pnml = doc.createElement("pnml")
pnml.setAttribute("xmlns", 'http://www.pnml.org/version-2009/grammar/pnml')
doc.appendChild(pnml)
net = doc.createElement("net")
net.setAttribute("id", "SPN")
# Important: set net type: stochastic
net.setAttribute("type", "Stochastic")
pnml.appendChild(net)
# build file body
c1 = 0 # places count
pdict = {}
c2 = 0 # trans count
c3 = 0 # inhib count
c4 = 0 # test count
# Set places, markings:
for spe in self.vdict['p']:
s = doc.createElement("place")
s.setAttribute("id", spe)
if self.vdict['c'] != None:
s.setAttribute("capacity",str(self.vdict['c'][c1]))
pdict[c1] = spe
m = doc.createElement("initialMarking")
v = doc.createElement("value")
amount = doc.createTextNode(str(int(self.vdict['m'][c1])))
v.appendChild(amount)
m.appendChild(v)
s.appendChild(m)
net.appendChild(s)
c1 += 1
# Set transitions, rates:
for reac in self.vdict['t']:
r = doc.createElement("transition")
r.setAttribute("id", reac)
rate = doc.createElement("rate")
v = doc.createElement("value")
amount = doc.createTextNode(str(self.vdict['r'][c2]))
v.appendChild(amount)
rate.appendChild(v)
r.appendChild(rate)
net.appendChild(r)
c2+=1
# Set Inhibitory arcs:
try:
if len(self.mdict['inhib']) != 0:
for iarc in self.mdict['inhib']:
for h in range(0,c1):
if iarc[0,h] != 0:
inhib = doc.createElement("arc")
inhib.setAttribute("source",self.vdict['p'][h])
inhib.setAttribute("target",self.vdict['t'][c3])
inhib.setAttribute("type","inhibitory")
inis = doc.createTextNode(str(iarc[0,h]))
va = doc.createElement("value")
va.appendChild(inis)
inhib.appendChild(va)
net.appendChild(inhib)
c3+=1
except TypeError:
pass
# Set Test arcs:
try:
if len(self.mdict['test']) != 0:
for tarc in self.mdict['test']:
for bx in range(0,c1):
if tarc[0,bx] != 0:
tar = doc.createElement("arc")
tar.setAttribute("source",self.vdict['p'][bx])
tar.setAttribute("target",self.vdict['t'][c4])
tar.setAttribute("type","test")
tis = doc.createTextNode(str(tarc[0,bx]))
val = doc.createElement("value")
val.appendChild(tis)
tar.appendChild(val)
net.appendChild(tar)
c4+=1
except TypeError:
pass
#.........这里部分代码省略.........
示例12: writeXacro
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def writeXacro(self):
# Create document
doc = Document()
# Create comment
comment = doc.createComment('WARNING: This file was auto-generated by csv2xacro_node.py. It should not be edited by hand.')
doc.appendChild(comment)
# Create root label
root = doc.createElement('robot')
root.setAttribute( 'name', 'duckietown' )
root.setAttribute('xmlns:xacro', 'http://www.ros.org/wiki/xacro')
doc.appendChild(root)
# Create Parameters comment
comment = doc.createComment('Parameters')
root.appendChild(comment)
# Create tile width
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','tile_width')
tempChild.setAttribute('value',str(self.tile_width))
root.appendChild(tempChild)
# Create tag offsets
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_0')
tempChild.setAttribute('value','%s %s'%(str(self.tag_offset), str(self.tag_curb)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_1')
tempChild.setAttribute('value','%s %s'%(str(self.tag_curb), str(self.tag_offset)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_2')
tempChild.setAttribute('value','%s %s'%(str(-self.tag_curb), str(self.tag_offset)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_3')
tempChild.setAttribute('value','%s %s'%(str(-self.tag_offset), str(self.tag_curb)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_4')
tempChild.setAttribute('value','%s %s'%(str(-self.tag_offset), str(-self.tag_curb)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_5')
tempChild.setAttribute('value','%s %s'%(str(-self.tag_curb), str(-self.tag_offset)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_6')
tempChild.setAttribute('value','%s %s'%(str(self.tag_curb), str(-self.tag_offset)))
root.appendChild(tempChild)
tempChild = doc.createElement('xacro:property')
tempChild.setAttribute('name','pos_7')
tempChild.setAttribute('value','%s %s'%(str(self.tag_offset), str(-self.tag_curb)))
root.appendChild(tempChild)
# Create comment
comment = doc.createComment('Include the tile and tag macros')
root.appendChild(comment)
# Create file name
tempChild = doc.createElement('xacro:include')
tempChild.setAttribute('filename','$(find duckietown_description)/urdf/macros.urdf.xacro')
root.appendChild(tempChild)
# Create comment
comment = doc.createComment('The world frame is at the lower left corner of duckietown')
root.appendChild(comment)
# Create link
tempChild = doc.createElement('link')
tempChild.setAttribute('name','world')
root.appendChild(tempChild)
# Create comment
comment = doc.createComment('Describe the tiles')
root.appendChild(comment)
# Create tiles
header = True
x_max = 0
y_max = 0
for row in self.tile_csv:
if header or row[0].isspace():
header = False
continue
x = row[0].strip('" ')
if int(x) > x_max:
x_max = int(x)
#.........这里部分代码省略.........
示例13: T
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
class T(basecanvas.T):
def __init__(self, fname):
basecanvas.T.__init__(self)
self.__out_fname = fname
self.__xmin, self.__xmax, self.__ymin, self.__ymax = 0,0,0,0
self.__doc = Document()
self.__doc.appendChild(self.__doc.createComment
('Created by PyChart ' + version.version + ' ' + version.copyright))
self.__svg = self.__doc.createElement('svg') # the svg doc
self.__doc.appendChild(self.__svg)
self.__defs = self.__doc.createElement('defs') # for clip paths
self.__svg.appendChild(self.__defs)
self.__currElt = self.__svg
self.gsave() # create top-level group for dflt styles
self._updateStyle(font_family = theme.default_font_family,
font_size = theme.default_font_size,
font_style = 'normal',
font_weight = 'normal',
font_stretch = 'normal',
fill = 'none',
stroke = 'rgb(0,0,0)', #SVG dflt none, PS dflt blk
stroke_width = theme.default_line_width,
stroke_linejoin = 'miter',
stroke_linecap = 'butt',
stroke_dasharray = 'none')
def _updateStyle(self, **addstyledict):
elt = _protectCurrentChildren(self.__currElt)
# fetch the current styles for this node
mystyledict = _parseStyleStr(elt.getAttribute('style'))
# concat all parent style strings to get dflt styles for this node
parent,s = elt.parentNode,''
while parent.nodeType != Document.nodeType :
# prepend parent str so later keys will override earlier ones
s = parent.getAttribute('style') + s
parent = parent.parentNode
dfltstyledict = _parseStyleStr(s)
# Do some pre-processing on the caller-supplied add'l styles
# Convert '_' to '-' so caller can specify style tags as python
# variable names, eg. stroke_width => stroke-width.
# Also convert all RHS values to strs
for key in addstyledict.keys():
k = re.sub('_','-',key)
addstyledict[k] = str(addstyledict[key]) # all vals => strs
if (k != key) : del addstyledict[key]
for k in addstyledict.keys() :
if (mystyledict.has_key(k) or # need to overwrite it
(not dfltstyledict.has_key(k)) or # need to set it
dfltstyledict[k] != addstyledict[k]) : # need to override it
mystyledict[k] = addstyledict[k]
s = _makeStyleStr(mystyledict)
if s : elt.setAttribute('style',s)
self.__currElt = elt
####################################################################
# methods below define the pychart backend device API
# First are a set of methods to start, construct and finalize a path
def newpath(self): # Start a new path
if (self.__currElt.nodeName != 'g') :
raise OverflowError, "No containing group for newpath"
# Just insert a new 'path' element into the document
p = self.__doc.createElement('path')
self.__currElt.appendChild(p)
self.__currElt = p
# This set of methods add data to an existing path element,
# simply add to the 'd' (data) attribute of the path elt
def moveto(self, x, y): #
if (self.__currElt.nodeName != 'path') :
raise OverflowError, "No path for moveto"
d = ' '.join([self.__currElt.getAttribute('d'),'M',`x`,`-y`]).strip()
self.__currElt.setAttribute('d', d)
def lineto(self, x, y):
if (self.__currElt.nodeName != 'path') :
raise OverflowError, "No path for lineto"
d = ' '.join([self.__currElt.getAttribute('d'),'L',`x`,`-y`]).strip()
self.__currElt.setAttribute('d', d)
def path_arc(self, x, y, radius, ratio, start_angle, end_angle):
# mimic PS 'arc' given radius, yr/xr (=eccentricity), start and
# end angles. PS arc draws from CP (if exists) to arc start,
# then draws arc in counterclockwise dir from start to end
# SVG provides an arc command that draws a segment of an
# ellipse (but not a full circle) given these args:
# A xr yr rotate majorArcFlag counterclockwiseFlag xe ye
# We don't use rotate(=0) and flipped axes => all arcs are clockwise
if (self.__currElt.nodeName != 'path') :
raise OverflowError, "No path for path_arc"
self.comment('x=%g, y=%g, r=%g, :=%g, %g-%g'
% (x,y,radius,ratio,start_angle,end_angle))
#.........这里部分代码省略.........
示例14: create_classifier_file
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
def create_classifier_file(self):
"""
Write the cascade classifier information into a xml file.
"""
#create instance of DOM
doc = Document()
#create root element
cascade_classifier_xml = doc.createElement('cascade_frontal_face')
cascade_classifier_xml.setAttribute('type_id', 'yao_cascade_classifier')
doc.appendChild(cascade_classifier_xml)
#sample size
sample_size = doc.createElement('size')
sample_size.setAttribute('w', str(self.sample_width))
sample_size.setAttribute('h', str(self.sample_height))
cascade_classifier_xml.appendChild(sample_size)
#stage count
stage_count = 0
for strong_Classifier in self.cascade_classifiers:
#stage information
stage_info = doc.createElement('stages')
stage_info.setAttribute('threshold', str(strong_Classifier.threshold))
stage_comment = doc.createComment('stage-'+str(stage_count))
stage_info.appendChild(stage_comment)
cascade_classifier_xml.appendChild(stage_info)
stage_count += 1
#tree node count
tree_count = 0
for weak_classifier in strong_Classifier.classifiers:
#decision tree node information
tree_info = doc.createElement('trees')
tree_comment = doc.createComment('tree-'+str(tree_count))
tree_info.appendChild(tree_comment)
stage_info.appendChild(tree_info)
tree_count += 1
#feature information
feature_info = doc.createElement('features')
#feature type
feature_type = doc.createElement('feature_type')
feature_type.setAttribute('type', str(weak_classifier.feature.type))
feature_info.appendChild(feature_type)
#feature position
feature_pos = doc.createElement('pos')
feature_pos.setAttribute('x', str(weak_classifier.feature.x))
feature_pos.setAttribute('y', str(weak_classifier.feature.y))
feature_info.appendChild(feature_pos)
#feature size
feature_size = doc.createElement('size')
feature_info.appendChild(feature_size)
feature_size.setAttribute('w', str(weak_classifier.feature.w))
feature_size.setAttribute('h', str(weak_classifier.feature.h))
#feature scaled size
feature_scaled = doc.createElement('scaled')
feature_info.appendChild(feature_scaled)
feature_scaled.setAttribute('x_axis', str(weak_classifier.feature.axis_x_scaled))
feature_scaled.setAttribute('y_axis', str(weak_classifier.feature.axis_y_scaled))
tree_info.appendChild(feature_info)
#threshold
threshold = doc.createElement('threshold')
threshold_node = doc.createTextNode(str(weak_classifier.threshold))
threshold.appendChild(threshold_node)
tree_info.appendChild(threshold)
#flag
flag = doc.createElement('flag')
flag_node = doc.createTextNode(str(weak_classifier.flag))
flag.appendChild(flag_node)
tree_info.appendChild(flag)
#widget
widget = doc.createElement('widget')
widget_node = doc.createTextNode(str(weak_classifier.widget))
widget.appendChild(widget_node)
tree_info.appendChild(widget)
#write to file
f = open('cascade_classifier.xml','w')
f.write(doc.toprettyxml(indent = ' '))
f.close()
示例15: RssApiWriter
# 需要导入模块: from xml.dom.minidom import Document [as 别名]
# 或者: from xml.dom.minidom.Document import createComment [as 别名]
#.........这里部分代码省略.........
content = ''
name = field_info[0]
if not hasattr(result, name) and len(field_info) > 1:
name = field_info[1]
if hasattr(result, name):
try:
content = str(getattr(result, name, ''))
except UnicodeEncodeError:
content = getattr(result, name, '').encode('ascii', 'ignore')
if name == "enddate":
if custom_date_format(content) == 'Present':
content = ''
elif name == "description":
if result_set.args.get('fulldesc', '') != '1':
content = content[:300]
elif name in ["eventrangestart", "eventrangeend"]:
content = content.replace('T', ' ').strip('Z')
return (name, content, None)
item = self.doc.createElement('item')
self.channel.appendChild(item)
#standard RSS fields
standard_fields = [
('title',),
('link', 'xml_url'),
('description', 'snippet'),
('pubDate',),
('guid', 'xml_url')
]
added_list = []
for field in standard_fields:
(name, content, comment) = build_result_element(field, result)
if len(name) < 3:
continue
if name == 'xml_url':
name = 'link'
else:
name = API_FIELD_NAMES_MAP.get(name, name)
if name in added_list:
continue
added_list.append(name)
if comment:
item.appendChild(self.doc.createComment(comment))
subitem = self.doc.createElement(name)
if content:
text = self.doc.createTextNode(content)
subitem.appendChild(text)
item.appendChild(subitem)
#and now our namespaced fields
namespaced_fields = FIELD_TUPLES
added_list = []
for field_info in namespaced_fields:
(name, content, comment) = build_result_element(field_info, result)
name = self.OurNamespace + ':' + API_FIELD_NAMES_MAP.get(name, name)
if (not result_set.is_hoc and not result_set.is_rss) and name.lower() not in STANDARD_FIELDS:
continue
if result_set.is_cal and name.lower() not in CALENDAR_FIELDS:
continue
if name in added_list:
continue
added_list.append(name)
if comment:
item.appendChild(self.doc.createComment(comment))
subitem = self.doc.createElement(name)
if content:
if len(field_info) > 1 and isinstance(content, basestring) and content.find('\t') > 0:
content = content.split('\t')
if isinstance(content, list):
for value in content:
subsubitem = self.doc.createElement(self.OurNamespace + ':' + field_info[1])
text = self.doc.createTextNode(value)
subsubitem.appendChild(text)
subitem.appendChild(subsubitem)
else:
text = self.doc.createTextNode(content)
subitem.appendChild(text)
item.appendChild(subitem)
def finalize(self):
"""Return a string from the XML document."""
#return self.doc.toxml(encoding='utf-8')
return self.doc.toprettyxml(indent=' ', newl='\n', encoding='utf-8')