wikiextractor/extractPage.py

139 lines
4.3 KiB
Python
Raw Normal View History

2015-03-22 20:45:17 +08:00
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# =============================================================================
2016-02-15 08:22:38 +08:00
# Version: 2.9 (Feb 13, 2016)
2015-03-22 20:45:17 +08:00
# Author: Giuseppe Attardi (attardi@di.unipi.it), University of Pisa
# =============================================================================
# Copyright (c) 2009. Giuseppe Attardi (attardi@di.unipi.it).
# =============================================================================
# This file is part of Tanl.
#
# Tanl is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License, version 3,
# as published by the Free Software Foundation.
#
# Tanl is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# =============================================================================
"""Wikipedia Page Extractor:
Extracts a single page from a Wikipedia dump file.
"""
import sys, os.path
import re, random
import argparse
from itertools import izip
import logging, traceback
import urllib
import bz2, gzip
from htmlentitydefs import name2codepoint
import Queue, threading, multiprocessing
# Program version
2016-02-15 08:22:38 +08:00
version = '2.9'
2015-03-22 20:45:17 +08:00
# ----------------------------------------------------------------------
# READER
tagRE = re.compile(r'(.*?)<(/?\w+)[^>]*>(?:([^<]*)(<.*?>)?)?')
#tagRE = re.compile(r'(.*?)<(/?\w+)[^>]*>([^<]*)')
# 1 2 3
2016-02-15 08:22:38 +08:00
def process_data(input_file, ids, templates=False):
2015-03-22 20:45:17 +08:00
"""
:param input_file: name of the wikipedia dump file.
2016-02-15 08:22:38 +08:00
:param ids: article ids (single or range first-last).
:param templates: collect also templates
2015-03-22 20:45:17 +08:00
"""
if input_file.lower().endswith("bz2"):
opener = bz2.BZ2File
else:
opener = open
input = opener(input_file)
2016-02-15 08:22:38 +08:00
print '<mediawiki>'
2015-03-22 20:45:17 +08:00
2016-02-15 08:22:38 +08:00
rang = ids.split('-')
first = int(rang[0])
if len(rang) == 1:
last = first
else:
last = int(rang[1])
2015-03-22 20:45:17 +08:00
page = []
2016-02-15 08:22:38 +08:00
curid = 0
2015-03-22 20:45:17 +08:00
for line in input:
line = line.decode('utf-8')
if '<' not in line: # faster than doing re.search()
if page:
page.append(line)
continue
m = tagRE.search(line)
if not m:
continue
tag = m.group(2)
if tag == 'page':
page = []
page.append(line)
inArticle = False
2016-02-15 08:22:38 +08:00
elif tag == 'id' and not curid: # other <id> are present
curid = int(m.group(3))
if first <= curid <= last:
2015-03-22 20:45:17 +08:00
page.append(line)
inArticle = True
2016-02-15 08:22:38 +08:00
elif curid > last and not templates:
break
2015-03-22 20:45:17 +08:00
elif not inArticle and not templates:
page = []
elif tag == 'title':
if templates:
if m.group(3).startswith('Template:'):
page.append(line)
else:
page = []
else:
page.append(line)
elif tag == '/page':
if page:
page.append(line)
print ''.join(page).encode('utf-8')
2016-02-15 08:22:38 +08:00
if not templates and curid == last:
2015-03-22 20:45:17 +08:00
break
2016-02-15 08:22:38 +08:00
curid = 0
2015-03-22 20:45:17 +08:00
page = []
elif page:
page.append(line)
2016-02-15 08:22:38 +08:00
print '</mediawiki>'
2015-03-22 20:45:17 +08:00
input.close()
def main():
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
formatter_class=argparse.RawDescriptionHelpFormatter,
description=__doc__)
parser.add_argument("input",
help="XML wiki dump file")
parser.add_argument("--id", default="",
2016-02-15 08:22:38 +08:00
help="article number, or range first-last")
2015-03-22 20:45:17 +08:00
parser.add_argument("--template", action="store_true",
2016-02-15 08:22:38 +08:00
help="extract also all templates")
2015-03-22 20:45:17 +08:00
parser.add_argument("-v", "--version", action="version",
version='%(prog)s ' + version,
help="print program version")
args = parser.parse_args()
2015-04-15 20:30:55 +08:00
2015-03-22 20:45:17 +08:00
process_data(args.input, args.id, args.template)
if __name__ == '__main__':
main()