A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

209 行
7.6 KiB

  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012 Ben Kurtovic <ben.kurtovic@verizon.net>
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. from collections import defaultdict
  23. import re
  24. from . import HTMLEntity, Node, Text
  25. from .extras import Parameter
  26. from ..utils import parse_anything
  27. __all__ = ["Template"]
  28. FLAGS = re.DOTALL | re.UNICODE
  29. class Template(Node):
  30. def __init__(self, name, params=None):
  31. self._name = name
  32. if params:
  33. self._params = params
  34. else:
  35. self._params = []
  36. def __unicode__(self):
  37. if self.params:
  38. params = u"|".join([unicode(param) for param in self.params])
  39. return "{{" + unicode(self.name) + "|" + params + "}}"
  40. else:
  41. return "{{" + unicode(self.name) + "}}"
  42. def __iternodes__(self, getter):
  43. yield None, self
  44. for child in getter(self.name):
  45. yield self.name, child
  46. for param in self.params:
  47. if param.showkey:
  48. for child in getter(param.name):
  49. yield param.name, child
  50. for child in getter(param.value):
  51. yield param.value, child
  52. def __showtree__(self, write, get, mark):
  53. write("{{")
  54. get(self.name)
  55. for param in self.params:
  56. write(" | ")
  57. mark()
  58. get(param.name)
  59. write(" = ")
  60. mark()
  61. get(param.value)
  62. write("}}")
  63. def _surface_escape(self, code, char):
  64. replacement = HTMLEntity(value=ord(char))
  65. for node in code.filter_text(recursive=False):
  66. if char in node:
  67. code.replace(node, node.replace(char, replacement))
  68. def _blank_param_value(self, value):
  69. match = re.search(r"^(\s*).*?(\s*)$", unicode(value), FLAGS)
  70. value.nodes = [Text(match.group(1)), Text(match.group(2))]
  71. def _select_theory(self, theories):
  72. if theories:
  73. best = max(theories.values())
  74. confidence = float(best) / sum(theories.values())
  75. if confidence > 0.75:
  76. return theories.keys()[theories.values().index(best)]
  77. def _get_spacing_conventions(self):
  78. before_theories = defaultdict(lambda: 0)
  79. after_theories = defaultdict(lambda: 0)
  80. for param in self.params:
  81. match = re.search(r"^(\s*).*?(\s*)$", unicode(param.value), FLAGS)
  82. before, after = match.group(1), match.group(2)
  83. before_theories[before] += 1
  84. after_theories[after] += 1
  85. before = self._select_theory(before_theories)
  86. after = self._select_theory(after_theories)
  87. return before, after
  88. def _remove_with_field(self, param, i, name):
  89. if param.showkey:
  90. following = self.params[i+1:]
  91. better_matches = [after.name.strip() == name and not after.showkey for after in following]
  92. if any(better_matches):
  93. return False
  94. return True
  95. def _remove_without_field(self, param, i, force_no_field):
  96. if not param.showkey and not force_no_field:
  97. dependents = [not after.showkey for after in self.params[i+1:]]
  98. if any(dependents):
  99. return False
  100. return True
  101. @property
  102. def name(self):
  103. return self._name
  104. @property
  105. def params(self):
  106. return self._params
  107. def has_param(self, name, ignore_empty=True):
  108. name = name.strip() if isinstance(name, basestring) else unicode(name)
  109. for param in self.params:
  110. if param.name.strip() == name:
  111. if ignore_empty and not param.value.strip():
  112. continue
  113. return True
  114. return False
  115. def get(self, name):
  116. name = name.strip() if isinstance(name, basestring) else unicode(name)
  117. for param in reversed(self.params):
  118. if param.name.strip() == name:
  119. return param
  120. raise ValueError(name)
  121. def add(self, name, value, showkey=None, force_nonconformity=False):
  122. name, value = parse_anything(name), parse_anything(value)
  123. self._surface_escape(value, "|")
  124. if self.has_param(name):
  125. self.remove(name, keep_field=True)
  126. existing = self.get(name)
  127. if showkey is not None:
  128. if not showkey:
  129. self._surface_escape(value, "=")
  130. existing.showkey = showkey
  131. nodes = existing.value.nodes
  132. if force_nonconformity:
  133. existing.value = value
  134. else:
  135. existing.value = parse_anything([nodes[0], value, nodes[1]])
  136. return existing
  137. if showkey is None:
  138. try:
  139. int_name = int(unicode(name))
  140. except ValueError:
  141. showkey = True
  142. else:
  143. int_keys = set()
  144. for param in self.params:
  145. if not param.showkey:
  146. if re.match(r"[1-9][0-9]*$", param.name.strip()):
  147. int_keys.add(int(unicode(param.name)))
  148. expected = min(set(range(1, len(int_keys) + 2)) - int_keys)
  149. if expected == int_name:
  150. showkey = False
  151. else:
  152. showkey = True
  153. if not showkey:
  154. self._surface_escape(value, "=")
  155. if not force_nonconformity:
  156. before, after = self._get_spacing_conventions()
  157. if before and after:
  158. value = parse_anything([before, value, after])
  159. elif before:
  160. value = parse_anything([before, value])
  161. elif after:
  162. value = parse_anything([value, after])
  163. param = Parameter(name, value, showkey)
  164. self.params.append(param)
  165. return param
  166. def remove(self, name, keep_field=False, force_no_field=False):
  167. name = name.strip() if isinstance(name, basestring) else unicode(name)
  168. removed = False
  169. for i, param in enumerate(self.params):
  170. if param.name.strip() == name:
  171. if keep_field:
  172. if self._remove_with_field(param, i, name):
  173. self._blank_param_value(param.value)
  174. keep_field = False
  175. else:
  176. self.params.remove(param)
  177. else:
  178. if self._remove_without_field(param, i, force_no_field):
  179. self.params.remove(param)
  180. else:
  181. self._blank_param_value(param.value)
  182. if not removed:
  183. removed = True
  184. if not removed:
  185. raise ValueError(name)