A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

152 lines
5.7 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 mwparserfromhell.nodes import HTMLEntity, Node, Text
  25. from mwparserfromhell.nodes.extras import Parameter
  26. from mwparserfromhell.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 _surface_escape(self, code, char):
  43. replacement = HTMLEntity(value=ord(char))
  44. for node in code.filter_text(recursive=False):
  45. if char in node:
  46. code.replace(node, node.replace(char, replacement))
  47. def _blank_param_value(self, value):
  48. match = re.search("^(\s*).*?(\s*)$", unicode(value), FLAGS)
  49. value.nodes = [Text(match.group(1)), Text(match.group(2))]
  50. def _select_theory(self, theories):
  51. if theories:
  52. best = max(theories.values())
  53. confidence = float(best) / sum(theories.values())
  54. if confidence > 0.75:
  55. return theories.keys()[theories.values().index(best)]
  56. def _get_spacing_conventions(self):
  57. before_theories = defaultdict(lambda: 0)
  58. after_theories = defaultdict(lambda: 0)
  59. for param in self.params:
  60. match = re.search("^(\s*).*?(\s*)$", unicode(param.value), FLAGS)
  61. before, after = match.group(1), match.group(2)
  62. before_theories[before] += 1
  63. after_theories[after] += 1
  64. before = self._select_theory(before_theories)
  65. after = self._select_theory(after_theories)
  66. return before, after
  67. @property
  68. def name(self):
  69. return self._name
  70. @property
  71. def params(self):
  72. return self._params
  73. def has_param(self, name, ignore_empty=True):
  74. name = name.strip() if isinstance(name, basestring) else unicode(name)
  75. for param in self.params:
  76. if param.name.strip() == name:
  77. if ignore_empty and not param.value.strip():
  78. continue
  79. return True
  80. return False
  81. def get(self, name):
  82. name = name.strip() if isinstance(name, basestring) else unicode(name)
  83. for param in self.params:
  84. if param.name.strip() == name:
  85. return param
  86. raise ValueError(name)
  87. def add(self, name, value, showkey=None, force_nonconformity=False):
  88. name, value = parse_anything(name), parse_anything(value)
  89. self._surface_escape(value, "|")
  90. if self.has_param(name):
  91. self.remove(name, keep_field=True)
  92. existing = self.get(name)
  93. if showkey is None: # Infer showkey from current value
  94. showkey = existing.showkey
  95. if not showkey:
  96. self._surface_escape(value, "=")
  97. nodes = existing.value.nodes
  98. if force_nonconformity:
  99. existing.value = value
  100. else:
  101. existing.value = parse_anything([nodes[0], value, nodes[1]])
  102. return existing
  103. if showkey is None:
  104. try:
  105. int(name)
  106. showkey = True
  107. except ValueError:
  108. showkey = False
  109. if not showkey:
  110. self._surface_escape(value, "=")
  111. if not force_nonconformity:
  112. before, after = self._get_spacing_conventions()
  113. if before and after:
  114. value = parse_anything([before, value, after])
  115. elif before:
  116. value = parse_anything([before, value])
  117. elif after:
  118. value = parse_anything([value, after])
  119. param = Parameter(name, value, showkey)
  120. self.params.append(param)
  121. return param
  122. def remove(self, name, keep_field=False, force_no_field=False):
  123. name = name.strip() if isinstance(name, basestring) else unicode(name)
  124. for i, param in enumerate(self.params):
  125. if param.name.strip() == name:
  126. if keep_field:
  127. return self._blank_param_value(param.value)
  128. dependent = [not after.showkey for after in self.params[i+1:]]
  129. if any(dependent) and not param.showkey and not force_no_field:
  130. return self._blank_param_value(param.value)
  131. return self.params.remove(param)
  132. raise ValueError(name)