如何通过python从mediawiki标记的文章中解析/提取数据 [英] How to parse/extract data from a mediawiki marked-up article via python

查看:38
本文介绍了如何通过python从mediawiki标记的文章中解析/提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

源 Mediawiki 标记

现在我正在使用各种正则表达式将 mediawiki 标记中的数据解析"为列表/字典,以便可以使用文章中的元素.

Right now I'm using a variety of regexes to "parse" the data in the mediawiki mark-up into lists/dictionaries, so that elements within the article can be used.

这不是最好的方法,因为必须制作的案例数量很多.

This is hardly the best method, as the number of cases that have to be made are large.

如何将一篇文章的 mediawiki 标记解析为各种 Python 对象,以便可以使用其中的数据?

How would one parse an article's mediawiki markup into a variety of python objects so that the data within can be used?

例如:

  • 将所有标题提取到字典,用它的散列部分.
  • 获取所有跨维基链接,以及把它们放在一个列表中(我知道
    这可以通过 API 完成,但我会而是只有一个 API 调用
    减少带宽使用).
  • 提取所有图像名称并使用他们的部分

各种正则表达式可以实现上述目的,但我发现我必须制作的数字相当大.

A variety of regexes can achieve the above, but I'm finding the number I have to make rather large.

这是 mediawiki 非官方规范(我没有找到他们的官方 规范 有用).

Here's the mediawiki unofficial specification (I don't find their official specification as useful).

推荐答案

mwlib - MediaWiki 解析器和实用程序库

pediapress/mw​​lib:

mwlib 提供了一个用于解析 MediaWiki 文章并将其转换为不同输出格式的库.维基百科的打印/导出"功能使用 mwlib 从维基百科文章中生成 PDF 文档.

mwlib provides a library for parsing MediaWiki articles and converting them to different output formats. mwlib is used by wikipedia's "Print/export" feature in order to generate PDF documents from wikipedia articles.

这是文档页面.使用的旧文档页面有一个单行示例:

Here's the documentation page. The older doc page used have a one-liner example:

from mwlib.uparser import simpleparse
simpleparse("=h1=\n*item 1\n*item2\n==h2==\nsome [[Link|caption]] there\n")

如果您想了解它的实际使用方式,请参阅代码附带的测试用例.(mwlib/tests/test_git_parser.py> 来自存储库):

If you want to see how it's used in action, see the test cases that come with the code. (mwlib/tests/test_parser.py from git repository):

from mwlib import parser, expander, uparser
from mwlib.expander import DictDB
from mwlib.xfail import xfail
from mwlib.dummydb import DummyDB
from mwlib.refine import util, core

parse = uparser.simpleparse

def test_headings():
    r=parse(u"""
= 1 =
== 2 ==
= 3 =
""")

    sections = [x.children[0].asText().strip() for x in r.children if isinstance(x, parser.Section)]
    assert sections == [u"1", u"3"]

另见标记规范替代解析器 了解更多信息.

Also see Markup spec and Alternative parsers for more information.

这篇关于如何通过python从mediawiki标记的文章中解析/提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆