HRR Co., Ltd.

技術的な記録を残していくことを目的としています。1次情報を大事にしています。

Wikipediaのデータからプレーンテキストを出力

はじめに

Wikipediaのデータを出力する方法はいろいろあります。
その中のひとつ、Wikipedia Extractorを試してみました。

Wikipedia Extractor - Medialab

やり方

データはここから取得しました。
Index of /jawiki/latest/ jawiki-latest-pages-articles.xml.bz2

そして、データのあるディレクトリにPythonファイルをダウンロード。

$ curl -O http://medialab.di.unipi.it/Project/SemaWiki/Tools/WikiExtractor.py

バージョンを確認。

$ python WikiExtractor.py --version
WikiExtractor.py 2.55

オプションは公式ページにある通りです。

 -h, --help            show this help message and exit
 -o OUTPUT, --output OUTPUT
                       output directory
 -b n[KM], --bytes n[KM]
                       put specified bytes per output file (default is 1M)
 -B BASE, --base BASE  base URL for the Wikipedia pages
 -c, --compress        compress output files using bzip
 -l, --links           preserve links
 -ns ns1,ns2, --namespaces ns1,ns2
                       accepted namespaces
 -q, --quiet           suppress reporting progress info
 -s, --sections        preserve sections
 -a, --article         analyze a file containing a single article
 --templates TEMPLATES
                       use or create file containing templates
 -v, --version         print program version

引用元: http://medialab.di.unipi.it/wiki/Wikipedia_Extractor

私は下記の通りに実行しました。

$ python WikiExtractor.py --output ./text --bytes 500K jawiki-latest-pages-articles.xml

こんなディレクトリ構成になります。

$ ls -alR text/
text/:
合計 4
drwxrwxr-x. 3 user group   16 1230 20:27 .
drwxr-xr-x. 3 user group  111 1230 21:11 ..
drwxrwxr-x. 2 user group 4096 1230 21:11 AA

text/AA:
合計 19764
drwxrwxr-x. 2 user group   4096 1230 21:11 .
drwxrwxr-x. 3 user group     16 1230 20:27 ..
-rw-rw-r--. 1 user group 500699 1230 21:08 wiki_00
-rw-rw-r--. 1 user group 489585 1230 21:08 wiki_01
-rw-rw-r--. 1 user group 510798 1230 21:08 wiki_02

内容はこんな感じ。docタグに囲まれて1記事が出力されています。
url属性にあるURLが元記事のURLなのですが、h2タグに当たる部分が省かれていることがわかります。

<doc id="56" url="https://ja.wikipedia.org/wiki?curid=56" title="地理">
地理

地理(ちり、英: Geography)
「地理」という表現は古くからあり、有名なところでは漢書の『地理志』がある。
地理学とは、地球の表面と住民の状態、その相互関係を研究する学問である。
「地理」は、日本の学校で設置されている、「人間の生活に影響を与える地域的、社会的な構造」を学ぶための科目である。自然環境や産業環境などを含む環境を学習対象としている。小学校および中学校においては、歴史や公民と並び、社会科の一分野である。高等学校においては、最近は「地理歴史科」という教科の中の一科目となっており、「地理A」「地理B」に細分されている。

</doc>

気になる点

私はヘッダタグ部分もほしかったので、ちょっと残念。
そして、私の環境では、なぜか処理が途中で中断してしまいます。
食わせるファイルのサイズが大きかったからでしょうか。

$ python WikiExtractor.py --output ./text --bytes 500K jawiki-latest-pages-articles.xml
INFO: Loaded 0 templates in 0.0s
INFO: Starting page extraction from jawiki-latest-pages-articles.xml.
INFO: Using 1 extract processes.
zsh: killed     python WikiExtractor.py --output ./text --bytes 500K

さいごに

なかなか自分がほしい形式で出力してくれるものが見つかりませんね。
自分で作るのが一番なのかも…と思いました。

以上でした!