MediaWiki模板解析器和编辑器
项目描述
mwtemplates是一个基于MediaWiki预处理器DOM.php的Python重写的MediaWiki wikitext模板解析器和编辑器。已在python 2.7、3.3、3.4、3.5上进行测试
安装
该软件包位于PyPI,因此您可以使用pip、easy_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 的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | a265958c469d33d7609f91a263b321dee8afac89ba57d918b03ee59eba2a8a28 |
|
MD5 | 6ad21d1045fb3fecb2e456422b910e6f |
|
BLAKE2b-256 | df240fb60d8b32695def78bcd27adf749c178638a42dc3de4ea859a4b15290f2 |