A Python parser for MediaWiki wikicode https://mwparserfromhell.readthedocs.io/
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 

103 рядки
3.3 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 . import tokens
  23. __all__ = ["Tokenizer"]
  24. class BadRoute(Exception):
  25. pass
  26. class Tokenizer(object):
  27. START = object()
  28. END = object()
  29. def __init__(self):
  30. self._text = None
  31. self._head = 0
  32. self._stacks = []
  33. self._context = []
  34. def _push(self):
  35. self._stacks.append([])
  36. def _pop(self):
  37. return self._stacks.pop()
  38. def _write(self, token, stack=None):
  39. if stack is None:
  40. stack = self._stacks[-1]
  41. if not stack:
  42. stack.append(token)
  43. return
  44. last = stack[-1]
  45. if isinstance(token, tokens.Text) and isinstance(last, tokens.Text):
  46. last.text += token.text
  47. else:
  48. stack.append(token)
  49. def _read(self, delta=0, wrap=False):
  50. index = self._head + delta
  51. if index < 0 and (not wrap or abs(index) > len(self._text)):
  52. return self.START
  53. if index >= len(self._text):
  54. return self.END
  55. return self._text[index]
  56. def _parse_template(self):
  57. reset = self._head
  58. self._head += 2
  59. try:
  60. template = self._parse_until("}}")
  61. except BadRoute:
  62. self._head = reset
  63. self._write(tokens.Text(text=self._read()))
  64. else:
  65. self._write(tokens.TemplateOpen())
  66. self._stacks[-1] += template
  67. self._write(tokens.TemplateClose())
  68. def _parse_until(self, stop=None):
  69. self._push()
  70. while True:
  71. if self._read() is self.END:
  72. return self._pop()
  73. try:
  74. iter(stop)
  75. except TypeError:
  76. if self._read() is stop:
  77. return self._pop()
  78. else:
  79. if all([self._read(i) == stop[i] for i in xrange(len(stop))]):
  80. self._head += len(stop) - 1
  81. return self._pop()
  82. if self._read(0) == "{" and self._read(1) == "{":
  83. self._parse_template()
  84. else:
  85. self._write(tokens.Text(text=self._read()))
  86. self._head += 1
  87. def tokenize(self, text):
  88. self._text = list(text)
  89. return self._parse_until(stop=self.END)