-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_categories.py
102 lines (82 loc) · 2.55 KB
/
create_categories.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# -*- coding: utf-8 -*-
"""
Program to batch create categories.
The program expects a generator containing a list of page titles to be used as
base.
The following command line parameters are supported:
-always (not implemented yet) Don't ask, just do the edit.
-overwrite (not implemented yet).
-parent The name of the parent category.
-basename The base to be used for the new category names.
Example:
create_categories.py
-lang:commons
-family:commons
-links:User:Multichill/Wallonia
-parent:"Cultural heritage monuments in Wallonia"
-basename:"Cultural heritage monuments in"
"""
__version__ = '$Id$'
#
# (C) Multichill, 2011
# (C) xqt, 2011
#
# Distributed under the terms of the MIT license.
#
#
import os, sys, re, codecs
import urllib, httplib, urllib2
import catlib
import time
import socket
import StringIO
import wikipedia as pywikibot
import config
import pagegenerators
def createCategory(page, parent, basename):
title = page.title(withNamespace=False)
newpage = pywikibot.Page(pywikibot.getSite(u'commons', u'commons'),
u'Category:' + basename + u' ' + title)
newtext = u''
newtext += u'[[Category:' + parent + u'|' + title + u']]\n'
newtext += u'[[Category:' + title + u']]\n'
if not newpage.exists():
#FIXME: Add user prompting and -always option
pywikibot.output(newpage.title())
pywikibot.showDiff(u'', newtext)
comment = u'Creating new category'
#FIXME: Add exception handling
newpage.put(newtext, comment)
else:
#FIXME: Add overwrite option
pywikibot.output(u'%s already exists, skipping' % (newpage.title(),))
def main(args):
'''
Main loop. Get a generator and options.
'''
generator = None
parent = u''
basename = u''
always = False
genFactory = pagegenerators.GeneratorFactory()
for arg in pywikibot.handleArgs():
if arg == '-always':
always = True
elif arg.startswith('-parent:'):
parent = arg [len('-parent:'):].strip()
elif arg.startswith('-basename'):
basename = arg [len('-basename:'):].strip()
else:
genFactory.handleArg(arg)
generator = genFactory.getCombinedGenerator()
if generator:
for page in generator:
createCategory(page, parent, basename)
else:
pywikibot.output(u'No pages to work on')
pywikibot.output(u'All done')
if __name__ == "__main__":
try:
main(sys.argv[1:])
finally:
pywikibot.stopme()