Skip to content

Instantly share code, notes, and snippets.

@minhlab
Created April 14, 2017 09:43
Show Gist options
  • Save minhlab/3e16fc46446bc8eae3bbefd83d1b52ad to your computer and use it in GitHub Desktop.
Save minhlab/3e16fc46446bc8eae3bbefd83d1b52ad to your computer and use it in GitHub Desktop.
An attempt to count the number of pages (recursively) in a category in Wikipedia. It wasn't successful because the category of Vietnamese Wikipedia is cyclic and confusing.
# -*- coding: utf-8 -*-
import pywikibot
import sys
from collections import Counter
from random import randint
wiki = 'wikipedia'
lang = 'vi'
cat_titles = ur'''
# Khoa học tự nhiên
Địa chất học
Địa lý học
Hóa học
Khoa học máy tính
Logic
Sinh học
Thiên văn học
Toán học
Vật lý học
Y học
# Khoa học xã hội
Chính trị học
Giáo dục
Kinh tế học
Lịch sử
Luật pháp
Ngôn ngữ học
Nhân chủng học
Tâm lý học
Thần học
Triết học
Xã hội học
# Kỹ thuật
Công nghiệp
Cơ học
Điện tử học
Giao thông
Kiến trúc
Năng lượng
Người máy
Nông nghiệp
Quân sự
Y tế
# Văn hóa
Âm nhạc
Chính trị
Du lịch
Điện ảnh
Giải trí
Khiêu vũ
Nghệ thuật
Phong tục tập quán
Thần thoại
Thể thao
Thời trang
Tôn giáo
Văn học
'''.strip().split('\n')
count = Counter()
site = pywikibot.Site(code=lang, fam=wiki)
def catpath(article, category):
'''Find a path from the article to the category in category tree'''
p = pywikibot.Page(site, article)
visited = set()
paths = {p.title(): []}
cats = [p]
while cats:
cat = cats.pop(0)
if cat.title() in visited:
if cat.title() in paths[cat.title()][:-1]:
sys.stdout.write('Circle detected: ')
for t in paths[cat.title()]: sys.stdout.write(u'%s, ' %t)
sys.stdout.write('\n')
else:
visited.add(cat.title())
#print cat, category, cat.title()
if category == cat.title():
return paths[cat.title()]
base_path = paths[cat.title()]
for c in cat.categories():
paths[c.title()] = base_path + [c.title()]
cats.append(c)
return []
for cat_title in cat_titles:
if cat_title[0] != '#':
full_cat_title = ur'Thể loại:' + cat_title
cat = pywikibot.Category(site, title=full_cat_title)
print '%s: ' %cat_title
last_titles = []
for a in cat.articles(recurse=4, namespaces=0):
count[cat_title] += 1
last_titles.append(a.title())
if count[cat_title] % 100 == 0:
rand_title = last_titles[randint(0, len(last_titles)-1)]
sys.stdout.write(u'\t%d -- example: %s' %(count[cat_title], rand_title))
sys.stdout.write('(')
for t in catpath(rand_title, full_cat_title): sys.stdout.write(u'%s, ' %t)
sys.stdout.write(')\n')
last_titles = []
for cat_title in cat_titles:
if cat_title[0] == '#':
print cat_title
else:
print '%s: %d' %(cat_title, count[cat_title])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment