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.

преди 12 години
преди 11 години
преди 11 години
преди 10 години
преди 1 година
преди 12 години
преди 12 години
преди 12 години
преди 11 години
преди 12 години
преди 3 години
преди 12 години
преди 6 години
преди 12 години
преди 6 години
преди 6 години
преди 6 години
преди 12 години
преди 11 години
преди 6 години
преди 12 години
преди 10 години
преди 6 години
преди 12 години
преди 6 години
преди 12 години
преди 9 години
преди 9 години
преди 9 години
преди 7 години
преди 12 години
преди 12 години
преди 12 години
преди 6 години
преди 12 години
преди 10 години
преди 12 години
преди 12 години
преди 12 години
преди 12 години
преди 6 години
преди 12 години
преди 5 години
преди 10 години
преди 12 години
преди 12 години
преди 12 години
преди 3 години
преди 7 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. mwparserfromhell
  2. ================
  3. .. image:: https://api.travis-ci.com/earwig/mwparserfromhell.svg
  4. :alt: Build Status
  5. :target: https://travis-ci.org/earwig/mwparserfromhell
  6. .. image:: https://img.shields.io/coveralls/earwig/mwparserfromhell/main.svg
  7. :alt: Coverage Status
  8. :target: https://coveralls.io/r/earwig/mwparserfromhell
  9. **mwparserfromhell** (the *MediaWiki Parser from Hell*) is a Python package
  10. that provides an easy-to-use and outrageously powerful parser for MediaWiki_
  11. wikicode. It supports Python 3.8+.
  12. Developed by Earwig_ with contributions from `Σ`_, Legoktm_, and others.
  13. Full documentation is available on ReadTheDocs_. Development occurs on GitHub_.
  14. Installation
  15. ------------
  16. The easiest way to install the parser is through the `Python Package Index`_;
  17. you can install the latest release with ``pip install mwparserfromhell``
  18. (`get pip`_). Make sure your pip is up-to-date first, especially on Windows.
  19. Alternatively, get the latest development version::
  20. git clone https://github.com/earwig/mwparserfromhell.git
  21. cd mwparserfromhell
  22. python setup.py install
  23. The comprehensive unit testing suite requires `pytest`_ (``pip install pytest``)
  24. and can be run with ``python -m pytest``.
  25. Usage
  26. -----
  27. Normal usage is rather straightforward (where ``text`` is page text):
  28. >>> import mwparserfromhell
  29. >>> wikicode = mwparserfromhell.parse(text)
  30. ``wikicode`` is a ``mwparserfromhell.Wikicode`` object, which acts like an
  31. ordinary ``str`` object with some extra methods. For example:
  32. >>> text = "I has a template! {{foo|bar|baz|eggs=spam}} See it?"
  33. >>> wikicode = mwparserfromhell.parse(text)
  34. >>> print(wikicode)
  35. I has a template! {{foo|bar|baz|eggs=spam}} See it?
  36. >>> templates = wikicode.filter_templates()
  37. >>> print(templates)
  38. ['{{foo|bar|baz|eggs=spam}}']
  39. >>> template = templates[0]
  40. >>> print(template.name)
  41. foo
  42. >>> print(template.params)
  43. ['bar', 'baz', 'eggs=spam']
  44. >>> print(template.get(1).value)
  45. bar
  46. >>> print(template.get("eggs").value)
  47. spam
  48. Since nodes can contain other nodes, getting nested templates is trivial:
  49. >>> text = "{{foo|{{bar}}={{baz|{{spam}}}}}}"
  50. >>> mwparserfromhell.parse(text).filter_templates()
  51. ['{{foo|{{bar}}={{baz|{{spam}}}}}}', '{{bar}}', '{{baz|{{spam}}}}', '{{spam}}']
  52. You can also pass ``recursive=False`` to ``filter_templates()`` and explore
  53. templates manually. This is possible because nodes can contain additional
  54. ``Wikicode`` objects:
  55. >>> code = mwparserfromhell.parse("{{foo|this {{includes a|template}}}}")
  56. >>> print(code.filter_templates(recursive=False))
  57. ['{{foo|this {{includes a|template}}}}']
  58. >>> foo = code.filter_templates(recursive=False)[0]
  59. >>> print(foo.get(1).value)
  60. this {{includes a|template}}
  61. >>> print(foo.get(1).value.filter_templates()[0])
  62. {{includes a|template}}
  63. >>> print(foo.get(1).value.filter_templates()[0].get(1).value)
  64. template
  65. Templates can be easily modified to add, remove, or alter params. ``Wikicode``
  66. objects can be treated like lists, with ``append()``, ``insert()``,
  67. ``remove()``, ``replace()``, and more. They also have a ``matches()`` method
  68. for comparing page or template names, which takes care of capitalization and
  69. whitespace:
  70. >>> text = "{{cleanup}} '''Foo''' is a [[bar]]. {{uncategorized}}"
  71. >>> code = mwparserfromhell.parse(text)
  72. >>> for template in code.filter_templates():
  73. ... if template.name.matches("Cleanup") and not template.has("date"):
  74. ... template.add("date", "July 2012")
  75. ...
  76. >>> print(code)
  77. {{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{uncategorized}}
  78. >>> code.replace("{{uncategorized}}", "{{bar-stub}}")
  79. >>> print(code)
  80. {{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}
  81. >>> print(code.filter_templates())
  82. ['{{cleanup|date=July 2012}}', '{{bar-stub}}']
  83. You can then convert ``code`` back into a regular ``str`` object (for
  84. saving the page!) by calling ``str()`` on it:
  85. >>> text = str(code)
  86. >>> print(text)
  87. {{cleanup|date=July 2012}} '''Foo''' is a [[bar]]. {{bar-stub}}
  88. >>> text == code
  89. True
  90. Limitations
  91. -----------
  92. While the MediaWiki parser generates HTML and has access to the contents of
  93. templates, among other things, mwparserfromhell acts as a direct interface to
  94. the source code only. This has several implications:
  95. * Syntax elements produced by a template transclusion cannot be detected. For
  96. example, imagine a hypothetical page ``"Template:End-bold"`` that contained
  97. the text ``</b>``. While MediaWiki would correctly understand that
  98. ``<b>foobar{{end-bold}}`` translates to ``<b>foobar</b>``, mwparserfromhell
  99. has no way of examining the contents of ``{{end-bold}}``. Instead, it would
  100. treat the bold tag as unfinished, possibly extending further down the page.
  101. * Templates adjacent to external links, as in ``http://example.com{{foo}}``,
  102. are considered part of the link. In reality, this would depend on the
  103. contents of the template.
  104. * When different syntax elements cross over each other, as in
  105. ``{{echo|''Hello}}, world!''``, the parser gets confused because this cannot
  106. be represented by an ordinary syntax tree. Instead, the parser will treat the
  107. first syntax construct as plain text. In this case, only the italic tag would
  108. be properly parsed.
  109. **Workaround:** Since this commonly occurs with text formatting and text
  110. formatting is often not of interest to users, you may pass
  111. *skip_style_tags=True* to ``mwparserfromhell.parse()``. This treats ``''``
  112. and ``'''`` as plain text.
  113. A future version of mwparserfromhell may include multiple parsing modes to
  114. get around this restriction more sensibly.
  115. Additionally, the parser lacks awareness of certain wiki-specific settings:
  116. * `Word-ending links`_ are not supported, since the linktrail rules are
  117. language-specific.
  118. * Localized namespace names aren't recognized, so file links (such as
  119. ``[[File:...]]``) are treated as regular wikilinks.
  120. * Anything that looks like an XML tag is treated as a tag, even if it is not a
  121. recognized tag name, since the list of valid tags depends on loaded MediaWiki
  122. extensions.
  123. Integration
  124. -----------
  125. ``mwparserfromhell`` is used by and originally developed for EarwigBot_;
  126. ``Page`` objects have a ``parse`` method that essentially calls
  127. ``mwparserfromhell.parse()`` on ``page.get()``.
  128. If you're using Pywikibot_, your code might look like this:
  129. .. code-block:: python
  130. import mwparserfromhell
  131. import pywikibot
  132. def parse(title):
  133. site = pywikibot.Site()
  134. page = pywikibot.Page(site, title)
  135. text = page.get()
  136. return mwparserfromhell.parse(text)
  137. If you're not using a library, you can parse any page with the following
  138. Python 3 code (using the API_ and the requests_ library):
  139. .. code-block:: python
  140. import mwparserfromhell
  141. import requests
  142. API_URL = "https://en.wikipedia.org/w/api.php"
  143. def parse(title):
  144. params = {
  145. "action": "query",
  146. "prop": "revisions",
  147. "rvprop": "content",
  148. "rvslots": "main",
  149. "rvlimit": 1,
  150. "titles": title,
  151. "format": "json",
  152. "formatversion": "2",
  153. }
  154. headers = {"User-Agent": "My-Bot-Name/1.0"}
  155. req = requests.get(API_URL, headers=headers, params=params)
  156. res = req.json()
  157. revision = res["query"]["pages"][0]["revisions"][0]
  158. text = revision["slots"]["main"]["content"]
  159. return mwparserfromhell.parse(text)
  160. .. _MediaWiki: https://www.mediawiki.org
  161. .. _ReadTheDocs: https://mwparserfromhell.readthedocs.io
  162. .. _Earwig: https://en.wikipedia.org/wiki/User:The_Earwig
  163. .. _Σ: https://en.wikipedia.org/wiki/User:%CE%A3
  164. .. _Legoktm: https://en.wikipedia.org/wiki/User:Legoktm
  165. .. _GitHub: https://github.com/earwig/mwparserfromhell
  166. .. _Python Package Index: https://pypi.org/
  167. .. _get pip: https://pypi.org/project/pip/
  168. .. _pytest: https://docs.pytest.org/
  169. .. _Word-ending links: https://www.mediawiki.org/wiki/Help:Links#linktrail
  170. .. _EarwigBot: https://github.com/earwig/earwigbot
  171. .. _Pywikibot: https://www.mediawiki.org/wiki/Manual:Pywikibot
  172. .. _API: https://www.mediawiki.org/wiki/API:Main_page
  173. .. _requests: https://2.python-requests.org