python编程例子数词的数量-python学习之路——基础篇(3)模块(续)

1 classElement:2 """An XML element.3

4 This class is the reference implementation of the Element interface.5

6 An element's length is its number of subelements. That means if you7 want to check if an element is truly empty, you should check BOTH8 its length AND its text attribute.9

10 The element tag, attribute names, and attribute values can be either11 bytes or strings.12

13 *tag* is the element name. *attrib* is an optional dictionary containing14 element attributes. *extra* are additional element attributes given as15 keyword arguments.16

17 Example form:18 text...tail19

20 """

21

22 当前节点的标签名23 tag =None24 """The element's name."""

25

26 当前节点的属性27

28 attrib =None29 """Dictionary of the element's attributes."""

30

31 当前节点的内容32 text =None33 """

34 Text before first subelement. This is either a string or the value None.35 Note that if there is no text, this attribute may be either36 None or the empty string, depending on the parser.37

38 """

39

40 tail =None41 """

42 Text after this element's end tag, but before the next sibling element's43 start tag. This is either a string or the value None. Note that if there44 was no text, this attribute may be either None or an empty string,45 depending on the parser.46

47 """

48

49 def __init__(self, tag, attrib={}, **extra):50 if notisinstance(attrib, dict):51 raise TypeError("attrib must be dict, not %s" %(52 attrib.__class__.__name__,))53 attrib =attrib.copy()54 attrib.update(extra)55 self.tag =tag56 self.attrib =attrib57 self._children =[]58

59 def __repr__(self):60 return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))61

62 defmakeelement(self, tag, attrib):63 创建一个新节点64 """Create a new element with the same type.65

66 *tag* is a string containing the element name.67 *attrib* is a dictionary containing the element attributes.68

69 Do not call this method, use the SubElement factory function instead.70

71 """

72 return self.__class__(tag, attrib)73

74 defcopy(self):75 """Return copy of current element.76

77 This creates a shallow copy. Subelements will be shared with the78 original tree.79

80 """

81 elem =self.makeelement(self.tag, self.attrib)82 elem.text =self.text83 elem.tail =self.tail84 elem[:] =self85 returnelem86

87 def __len__(self):88 returnlen(self._children)89

90 def __bool__(self):91 warnings.warn(92 "The behavior of this method will change in future versions."

93 "Use specific 'len(elem)' or 'elem is not None' test instead.",94 FutureWarning, stacklevel=2

95 )96 return len(self._children) != 0 #emulate old behaviour, for now

97

98 def __getitem__(self, index):99 returnself._children[index]100

101 def __setitem__(self, index, element):102 #if isinstance(index, slice):

103 #for elt in element:

104 #assert iselement(elt)

105 #else:

106 #assert iselement(element)

107 self._children[index] =element108

109 def __delitem__(self, index):110 delself._children[index]111

112 defappend(self, subelement):113 为当前节点追加一个子节点114 """Add *subelement* to the end of this element.115

116 The new element will appear in document order after the last existing117 subelement (or directly after the text, if it's the first subelement),118 but before the end tag for this element.119

120 """

121 self._assert_is_element(subelement)122 self._children.append(subelement)123

124 defextend(self, elements):125 为当前节点扩展 n 个子节点126 """Append subelements from a sequence.127

128 *elements* is a sequence with zero or more elements.129

130 """

131 for element inelements:132 self._assert_is_element(element)133 self._children.extend(elements)134

135 definsert(self, index, subelement):136 在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置137 """Insert *subelement* at position *index*."""

138 self._assert_is_element(subelement)139 self._children.insert(index, subelement)140

141 def_assert_is_element(self, e):142 #Need to refer to the actual Python implementation, not the

143 #shadowing C implementation.

144 if notisinstance(e, _Element_Py):145 raise TypeError('expected an Element, not %s' % type(e).__name__)146

147 defremove(self, subelement):148 在当前节点在子节点中删除某个节点149 """Remove matching subelement.150

151 Unlike the find methods, this method compares elements based on152 identity, NOT ON tag value or contents. To remove subelements by153 other means, the easiest way is to use a list comprehension to154 select what elements to keep, and then use slice assignment to update155 the parent element.156

157 ValueError is raised if a matching element could not be found.158

159 """

160 #assert iselement(element)

161 self._children.remove(subelement)162

163 defgetchildren(self):164 获取所有的子节点(废弃)165 """(Deprecated) Return all subelements.166

167 Elements are returned in document order.168

169 """

170 warnings.warn(171 "This method will be removed in future versions."

172 "Use 'list(elem)' or iteration over elem instead.",173 DeprecationWarning, stacklevel=2

174 )175 returnself._children176

177 def find(self, path, namespaces=None):178 获取第一个寻找到的子节点179 """Find first matching element by tag name or path.180

181 *path* is a string having either an element tag or an XPath,182 *namespaces* is an optional mapping from namespace prefix to full name.183

184 Return the first matching element, or None if no element was found.185

186 """

187 returnElementPath.find(self, path, namespaces)188

189 def findtext(self, path, default=None, namespaces=None):190 获取第一个寻找到的子节点的内容191 """Find text for first matching element by tag name or path.192

193 *path* is a string having either an element tag or an XPath,194 *default* is the value to return if the element was not found,195 *namespaces* is an optional mapping from namespace prefix to full name.196

197 Return text content of first matching element, or default value if198 none was found. Note that if an element is found having no text199 content, the empty string is returned.200

201 """

202 returnElementPath.findtext(self, path, default, namespaces)203

204 def findall(self, path, namespaces=None):205 获取所有的子节点206 """Find all matching subelements by tag name or path.207

208 *path* is a string having either an element tag or an XPath,209 *namespaces* is an optional mapping from namespace prefix to full name.210

211 Returns list containing all matching elements in document order.212

213 """

214 returnElementPath.findall(self, path, namespaces)215

216 def iterfind(self, path, namespaces=None):217 获取所有指定的节点,并创建一个迭代器(可以被for循环)218 """Find all matching subelements by tag name or path.219

220 *path* is a string having either an element tag or an XPath,221 *namespaces* is an optional mapping from namespace prefix to full name.222

223 Return an iterable yielding all matching elements in document order.224

225 """

226 returnElementPath.iterfind(self, path, namespaces)227

228 defclear(self):229 清空节点230 """Reset element.231

232 This function removes all subelements, clears all attributes, and sets233 the text and tail attributes to None.234

235 """

236 self.attrib.clear()237 self._children =[]238 self.text = self.tail =None239

240 def get(self, key, default=None):241 获取当前节点的属性值242 """Get element attribute.243

244 Equivalent to attrib.get, but some implementations may handle this a245 bit more efficiently. *key* is what attribute to look for, and246 *default* is what to return if the attribute was not found.247

248 Returns a string containing the attribute value, or the default if249 attribute was not found.250

251 """

252 returnself.attrib.get(key, default)253

254 defset(self, key, value):255 为当前节点设置属性值256 """Set element attribute.257

258 Equivalent to attrib[key] = value, but some implementations may handle259 this a bit more efficiently. *key* is what attribute to set, and260 *value* is the attribute value to set it to.261

262 """

263 self.attrib[key] =value264

265 defkeys(self):266 获取当前节点的所有属性的 key267

268 """Get list of attribute names.269

270 Names are returned in an arbitrary order, just like an ordinary271 Python dict. Equivalent to attrib.keys()272

273 """

274 returnself.attrib.keys()275

276 defitems(self):277 获取当前节点的所有属性值,每个属性都是一个键值对278 """Get element attributes as a sequence.279

280 The attributes are returned in arbitrary order. Equivalent to281 attrib.items().282

283 Return a list of (name, value) tuples.284

285 """

286 returnself.attrib.items()287

288 def iter(self, tag=None):289 在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。290 """Create tree iterator.291

292 The iterator loops over the element and all subelements in document293 order, returning all elements with a matching tag.294

295 If the tree structure is modified during iteration, new or removed296 elements may or may not be included. To get a stable set, use the297 list() function on the iterator, and loop over the resulting list.298

299 *tag* is what tags to look for (default is to return all elements)300

301 Return an iterator containing all the matching elements.302

303 """

304 if tag == "*":305 tag =None306 if tag is None or self.tag ==tag:307 yieldself308 for e inself._children:309 yield frome.iter(tag)310

311 #compatibility

312 def getiterator(self, tag=None):313 #Change for a DeprecationWarning in 1.4

314 warnings.warn(315 "This method will be removed in future versions."

316 "Use 'elem.iter()' or 'list(elem.iter())' instead.",317 PendingDeprecationWarning, stacklevel=2

318 )319 returnlist(self.iter(tag))320

321 defitertext(self):322 在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。323 """Create text iterator.324

325 The iterator loops over the element and all subelements in document326 order, returning all inner text.327

328 """

329 tag =self.tag330 if not isinstance(tag, str) and tag is notNone:331 return

332 ifself.text:333 yieldself.text334 for e inself:335 yield frome.itertext()336 ife.tail:337 yielde.tail338

339 节点功能一览表

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值