Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); GitHub - 5j9/wikitextparser: A Python library to parse MediaWiki WikiText · GitHub
Skip to content

Repository files navigation

https://codecov.io/github/5j9/wikitextparser/coverage.svg?branch=masterhttps://readthedocs.org/projects/wikitextparser/badge/?version=latest

A simple to use WikiText parsing library for MediaWiki.

The purpose is to allow users easily extract and/or manipulate templates, template parameters, parser functions, tables, external links, wikilinks, lists, etc. found in wikitexts.

  • Python 3.8+ is required
  • pip install wikitextparser
>>>importwikitextparseraswtp

WikiTextParser can detect sections, parser functions, templates, wiki links, external links, arguments, tables, wiki lists, and comments in your wikitext. The following sections are a quick overview of some of these functionalities.

You may also want to have a look at the test modules for more examples and probable pitfalls (expected failures).

>>>parsed=wtp.parse("{{text|value1{{text|value2}}}}")
>>>parsed.templates
[Template('{{text|value1{{text|value2}}}}'), Template('{{text|value2}}')]
>>>parsed.templates[0].arguments
[Argument("|value1{{text|value2}}")]
>>>parsed.templates[0].arguments[0].value='value3'>>>print(parsed)
{{text|value3}}

The pformat method returns a pretty-print formatted string for templates:

>>>parsed=wtp.parse('{{t1 |b=b|c=c| d={{t2|e=e|f=f}} }}')
>>>t1, t2=parsed.templates>>>print(t2.pformat())
{{t2|e=e|f=f
}}
>>>print(t1.pformat())
{{t1|b=b|c=c|d= {{t2|e=e|f=f
}}
}}

Template.rm_dup_args_safe and Template.rm_first_of_dup_args methods can be used to clean-up pages using duplicate arguments in template calls:

>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_dup_args_safe()
>>>tTemplate('{{t|a=b|a=a}}')
>>>t=wtp.Template('{{t|a=a|a=b|a=a}}')
>>>t.rm_first_of_dup_args()
>>>tTemplate('{{t|a=a}}')

Template parameters:

>>>param=wtp.parse('{{{a|b}}}').parameters[0]
>>>param.name'a'>>>param.default'b'>>>param.default='c'>>>paramParameter('{{{a|c}}}')
>>>param.append_default('d')
>>>paramParameter('{{{a|{{{d|c}}}}}}')
>>>wl=wtp.parse('... [[title#fragmet|text]] ...').wikilinks[0]
>>>wl.title='new_title'>>>wl.fragment='new_fragmet'>>>wl.text='X'>>>wlWikiLink('[[new_title#new_fragmet|X]]')
>>>delwl.text>>>wlWikiLink('[[new_title#new_fragmet]]')

All WikiLink properties support get, set, and delete operations. Categories are special cases of WikiLinks, in that they are prefixed with the category namespace, which is case insensitive and may be internationalized:

>>>parsed=wtp.parse(""" [[Category:Foo]] [[Κατηγορία:Bar]] [[Other link]] """)
>>>categories= [
wlforwlinparsed.wikilinksifwl.title.partition(':')[0]
.strip()
.lower()
in ["category", "κατηγορία"]
]
>>>categories
[WikiLink('[[Category:Foo]]'), WikiLink('[[Category:Bar]]')]
>>>parsed=wtp.parse("""... == h2 ==... t2... === h3 ===... t3... === h3 ===... t3... == h22 ==... t22... {{text|value3}}... [[Z|X]]... """)
>>>parsed.sections
[Section('\n'),
Section('== h2 ==\nt2\n=== h3 ===\nt3\n=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('=== h3 ===\nt3\n'),
Section('== h22 ==\nt22\n{{text|value3}}\n[[Z|X]]\n')]
>>>parsed.sections[1].title='newtitle'>>>print(parsed)==newtitle==t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]
>>>delparsed.sections[1].title>>>>print(parsed)
t2===h3===t3===h3===t3==h22==t22
{{text|value3}}
[[Z|X]]

Extracting cell values of a table:

>>>p=wtp.parse("""{|... | Orange || Apple || more... |-... | Bread || Pie || more... |-... | Butter || Ice cream || and more... |}""")
>>>p.tables[0].data()
[['Orange', 'Apple', 'more'],
['Bread', 'Pie', 'more'],
['Butter', 'Ice cream', 'and more']]

By default, values are arranged according to colspan and rowspan attributes:

>>>t=wtp.Table("""{| class="wikitable sortable"... |-... ! a !! b !! c... |-... !colspan = "2" | d || e... |-... |}""")
>>>t.data()
[['a', 'b', 'c'], ['d', 'd', 'e']]
>>>t.data(span=False)
[['a', 'b', 'c'], ['d', 'e']]

Calling the cells method of a Table returns table cells as Cell objects. Cell objects provide methods for getting or setting each cell's attributes or values individually:

>>>cell=t.cells(row=1, column=1)
>>>cell.attrs
{'colspan': '2'}
>>>cell.set('colspan', '3')
>>>print(t)
{|class="wikitable sortable"|-
! a !! b !! c|-
!colspan="3"|d||e|-|}

HTML attributes of Table, Cell, and Tag objects are accessible via get_attr, set_attr, has_attr, and del_attr methods.

The get_lists method provides access to lists within the wikitext.

>>>parsed=wtp.parse(
... 'text\n'
... '* list item a\n'
... '* list item b\n'
... '** sub-list of b\n'
... '* list item c\n'
... '** sub-list of b\n'
... 'text'
... )
>>>wikilist=parsed.get_lists()[0]
>>>wikilist.items
[' list item a', ' list item b', ' list item c']

The sublists method can be used to get all sub-lists of the current list or just sub-lists of specific items:

>>>wikilist.sublists()
[WikiList('** sub-list of b\n'), WikiList('** sub-list of b\n')]
>>>wikilist.sublists(1)[0].items
[' sub-list of b']

It also has an optional pattern argument that works similar to lists, except that the current list pattern will be automatically added to it as a prefix:

>>>wikilist=wtp.WikiList('#a\n#b\n##ba\n#*bb\n#:bc\n#c', '\#')
>>>wikilist.sublists()
[WikiList('##ba\n'), WikiList('#*bb\n'), WikiList('#:bc\n')]
>>>wikilist.sublists(pattern='\*')
[WikiList('#*bb\n')]

Convert one type of list to another using the convert method. Specifying the starting pattern of the desired lists can facilitate finding them and improves the performance:

>>>wl=wtp.WikiList(
... ':*A1\n:*#B1\n:*#B2\n:*:continuing A1\n:*A2',
... pattern=':\*'
... )
>>>print(wl)
:*A1
:*#B1
:*#B2
:*:continuingA1
:*A2>>>wl.convert('#')
>>>print(wl)
#A1##B1##B2#:continuing A1#A2

Accessing HTML tags:

>>>p=wtp.parse('text<ref name="c">citation</ref>\n<references/>')
>>>ref, references=p.get_tags()
>>>ref.name='X'>>>refTag('<X name="c">citation</X>')
>>>referencesTag('<references/>')

WikiTextParser is able to handle common usages of HTML and extension tags. However it is not a fully-fledged HTML parser and may fail on edge cases or malformed HTML input. Please open an issue on github if you encounter bugs.

parent and ancestors methods can be used to access a node's parent or ancestors respectively:

>>>template_d=parse("{{a|{{b|{{c|{{d}}}}}}}}").templates[3]
>>>template_d.ancestors()
[Template('{{c|{{d}}}}'),
Template('{{b|{{c|{{d}}}}}}'),
Template('{{a|{{b|{{c|{{d}}}}}}}}')]
>>>template_d.parent()
Template('{{c|{{d}}}}')
>>> _.parent()
Template('{{b|{{c|{{d}}}}}}')
>>> _.parent()
Template('{{a|{{b|{{c|{{d}}}}}}}}')
>>> _.parent() # Returns None

Use the optional type_ argument if looking for ancestors of a specific type:

>>>parsed=parse('{{a|{{#if:{{b{{c<!---->}}}}}}}}')
>>>comment=parsed.comments[0]
>>>comment.ancestors(type_='ParserFunction')
[ParserFunction('{{#if:{{b{{c<!---->}}}}}}')]

To delete/remove any object from its parents use del object[:] or del object.string.

The remove_markup function or plain_text method can be used to remove wiki markup:

>>>fromwikitextparserimportremove_markup, parse>>>s="'''a'''<!--comment--> [[b|c]] [[d]]">>>remove_markup(s)
'a c d'>>>parse(s).plain_text()
'a c d'

mwparserfromhell is a mature and widely used library with nearly the same purposes as wikitextparser. The main reason leading me to create wikitextparser was that mwparserfromhell could not parse wikitext in certain situations that I needed it for. See mwparserfromhell's issues 40, 42, 88, and other related issues. In many of those situation wikitextparser may be able to give you more acceptable results.

Also note that wikitextparser is still using 0.x.y version meaning that the API is not stable and may change in the future versions.

The tokenizer in mwparserfromhell is written in C. Tokenization in wikitextparser is mostly done using the regex library which is also in C. I have not rigorously compared the two libraries in terms of performance, i.e. execution time and memory usage. In my limited experience, wikitextparser has a decent performance in realistic cases and should be able to compete and may even have little performance benefits in some situations.

If you have had a chance to compare these libraries in terms of performance or capabilities please share your experience by opening an issue on github.

Some of the unique features of wikitextparser are: Providing access to individual cells of each table, pretty-printing templates, a WikiList class with rudimentary methods to work with lists, and a few other functions.

  • The contents of templates/parameters are not known to offline parsers. For example an offline parser cannot know if the markup [[{{z|a}}]] should be treated as wikilink or not, it depends on the inner-workings of the {{z}} template. In these situations wikitextparser tries to use a best guess. [[{{z|a}}]] is treated as a wikilink (why else would anyone call a template inside wikilink markup, and even if it is not a wikilink, usually no harm is done).
  • Localized namespace names are unknown, so for example [[File:...]] links are treated as normal wikilinks. mwparserfromhell has similar issue, see #87 and #136. As a workaround, Pywikibot can be used for determining the namespace.
  • Linktrails are language dependant and are not supported. Also not supported by mwparserfromhell. However given the trail pattern and knowing that wikilink.span[1] is the ending position of a wikilink, it is possible to compute a WikiLink's linktrail.
  • Templates adjacent to external links are never considered part of the link. In reality, this depends on the contents of the template. Example: parse('http://example.com{{dead link}}').external_links[0].url == 'http://example.com'
  • List of valid extension tags depends on the extensions intalled on the wiki. The tags method currently only supports the ones on English Wikipedia. A configuration option might be added in the future to address this issue.
  • wikitextparser currently does not provide an ast.walk-like method yielding all descendant nodes.
  • Parser functions and magic words are not evaluated.

About

A Python library to parse MediaWiki WikiText

Topics

Resources

Stars

330 stars

Watchers

6 watching

Forks

Releases

Used by

Contributors

Languages