跳转到主要内容

MediaWiki模板解析器和编辑器

项目描述

Build status Test coverage Latest Version Supported Python versions Downloads

mwtemplates是一个基于MediaWiki预处理器DOM.php的Python重写的MediaWiki wikitext模板解析器和编辑器。已在python 2.7、3.3、3.4、3.5上进行测试

安装

该软件包位于PyPI,因此您可以使用pipeasy_install或类似工具进行安装

$ pip install -U mwtemplates

或者您可以从发布中获取最新的zip文件。

简介

让我们首先导入TemplateEditor并给它一些wikitext来处理

>>> from mwtemplates import TemplateEditor
>>> txt = u"""{{Infobox cheese
... | name = Mozzarella
... | protein = 7
... }}
... Mozzarella is a cheese…{{tr}}"""
>>> te = TemplateEditor(txt)

首先,我们可以看到编辑器在文本中找到了哪些模板

>>> te.templates
[<Template:"Infobox cheese" at line 2>, <Template:"Tr" at line 6>]

每个模板都是Template类的实例。注意,模板名称通过将第一个字符转换为大写来进行规范化。现在,我们可以尝试调查《Infobox cheese》模板

>>> te.templates['Infobox cheese']
[<Template:"Infobox cheese" at line 2>]

由于可能有多个相同模板的实例,所以总是返回一个数组,因此我们需要请求te.templates[‘Infobox cheese’][0]以获取实际的Template。要获取参数

>>> te.templates['Infobox cheese'][0].parameters
<Parameters: name="Mozzarella", protein="10">

假设我们想要将protein参数的值从10更改为7。然后我们使用wikitext()方法返回我们的新wikitext

>>> te.templates['Infobox cheese'][0].parameters['protein'] = 7
>>> print te.wikitext()
{{Infobox cheese
| name = Mozzarella
| protein = 10
}}
Mozzarella is a cheese{{tr}}

注意格式已保留。现在我们可以添加一个新的参数,如下所示

>>> te.templates['Infobox cheese'][0].parameters['fat'] = 25
>>> print te.wikitext()
{{Infobox cheese
| name = Mozzarella
| protein = 7
| fat = 25
}}
Mozzarella is a cheese{{tr}}

使用mwclient编辑维基百科页面

使用 mwclient 更新维基百科上的页面

from mwclient import Site
from mwtemplates import TemplateEditor

site = Site('en.wikipedia.org')
site.login('USERNAME', 'PASSWORD')
page = site.pages['SOME_PAGE']
te = TemplateEditor(page.text())
if 'SOME_TEMPLATE' in page.templates:
   tpl = te.templates['SOME_TEMPLATE'][0]
   tpl.parameters['test'] = 'Hello'
page.save(te.wikitext(), summary='...')

移除模板参数

from mwtemplates import TemplateEditor
te = TemplateEditor(u"Hello {{mytpl | a=2 | b=3 | c=4 }} world")
te.templates['mytpl'].parameters.remove('b')

移除模板的第一个实例

from mwtemplates import TemplateEditor
te = TemplateEditor(u"Hello {{mytpl}} world {{mytpl}}")
te.templates['mytpl'][0].remove()

贡献

欢迎提交拉取请求。请提交前运行测试

$ python setup.py test

项目详情


下载文件

下载适合您平台的文件。如果您不确定选择哪个,请了解更多关于 安装包 的信息。

源分发

mwtemplates-0.4.0.tar.gz (12.2 kB 查看哈希值)

上传时间

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面