rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print "Logging in to ",wikipedia.family.hostname(wikipedia.mylang)
wikipedia.output(u"Logging in to %s" % wikipedia.family.hostname(wikipedia.mylang))
def makepath(path): """ creates missing directories for the given path and returns a normalized absolute version of the path. - if the given path already exists in the filesystem the filesystem is not modified. - otherwise makepath creates directories along the given path using the dirname() of the path. You may appe...
username=raw_input('username: ') password=getpass.getpass('password: ')
username = wikipedia.input(u'username:', encode = True) password = getpass.getpass(u'password: ') password = unicode(password, config.console_encoding) password = password.encode(wikipedia.myencoding())
def makepath(path): """ creates missing directories for the given path and returns a normalized absolute version of the path. - if the given path already exists in the filesystem the filesystem is not modified. - otherwise makepath creates directories along the given path using the dirname() of the path. You may appe...
pass from_pl = ''
print "Can't work on redirect page." return from_pl = ""
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not found.') try: interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass
if from_pl == "": print "Interwiki link to " + from_lang + " not found." return
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
wikipedia.setAction(msg[msglang] + from_lang + ':' + from_pl.linkname())
wikipedia.setAction(msg[msglang] + from_lang + ":" + from_pl.linkname())
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
table = translate(table)
if not table: print "No table found in %s." % from_lang + ":" + from_pl.linkname() return table = translate(table, type) if not table: print "Could not translate table." return
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
to_text = table + '\n\n' + to_text
to_text = table + "\n\n" + to_text
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
print 'Changing page %s' % (to_pl)
print "Changing page %s" % (to_pl)
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
startR = re.compile(r'<table|\{\|')
startR = re.compile(r"<table|\{\|")
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
endR = re.compile(r'</table>|\|\}')
endR = re.compile(r"</table>|\|\}")
def treat(to_pl): try: to_text = to_pl.get() interwikis = to_pl.interwiki() except wikipedia.IsRedirectPage: pass from_pl = '' for interwiki in interwikis: if interwiki.code() == from_lang: from_pl = interwiki if from_pl == '': print 'Interwiki link to ' + from_lang + ' not found.' raise NoInterwiki('Interwiki link not...
if debug: print 'No table found' pass
return
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if debug: print 'First start tag found at ' + str(first_start_tag.start())
if debug: print "First start tag found at " + str(first_start_tag.start())
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if debug: print 'Error: missing end tag'
if debug: print "Error: missing end tag"
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if debug: print 'Next start tag found at ' + str(pos + next_start_tag.start())
if debug: print "Next start tag found at " + str(pos + next_start_tag.start())
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if debug: print 'Table level is ' + str(table_level)
if debug: print "Table level is " + str(table_level)
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if debug: print 'Next end tag found at ' + str(pos + next_end_tag.start())
if debug: print "Next end tag found at " + str(pos + next_end_tag.start())
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if debug: print 'Table level is ' + str(table_level) if debug: print 'Table starts at ' + str(first_start_tag.start()) + ' and ends at ' + str(pos)
if debug: print "Table level is " + str(table_level) if debug: print "Table starts at " + str(first_start_tag.start()) + " and ends at " + str(pos)
def get_table(text): pos = 0 # find first start tag first_start_tag = re.search(startR, text) if not first_start_tag: if debug: print 'No table found' pass else: if debug: print 'First start tag found at ' + str(first_start_tag.start()) pos = first_start_tag.end() table_level = 1 remaining_text = text while table_level...
if self.oldCat.copyTo(newCatTitle): if batchMode == False: if self.oldCat.isEmpty(): reason = wikipedia.translate(wikipedia.getSite(), deletion_reason_move) % newCatTitle self.oldCat.delete(reason)
if self.oldCat.copyAndKeep(newCatTitle, wikipedia.translate(wikipedia.getSite(), cfd_templates)): if self.oldCat.isEmpty(): reason = wikipedia.translate(wikipedia.getSite(), deletion_reason_move) % newCatTitle if batchMode == True: self.oldCat.delete(reason, False)
def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat) # TODO: cre...
wikipedia.output('Couldn\'t copy contents of %s because %s already exists.' % (self.oldCatTitle, self.newCatTitle))
self.oldCat.delete(reason, True) else: wikipedia.output('Couldn\'t copy contents of %s because %s already exists.' % (self.oldCatTitle, self.newCatTitle))
def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat) # TODO: cre...
if self.cat.exists() and self.cat.isEmpty() and batchMode == False:
if self.cat.exists() and self.cat.isEmpty():
def run(self): articles = self.cat.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in category %s' % self.cat.title()) else: for article in articles: catlib.change_category(article, self.cat, None) # Also removes the category tag from subcategories' pages subcategories = self.cat.s...
self.cat.delete(reason)
if batchMode == True: self.cat.delete(reason, False) else: self.cat.delete(reason, True)
def run(self): articles = self.cat.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in category %s' % self.cat.title()) else: for article in articles: catlib.change_category(article, self.cat, None) # Also removes the category tag from subcategories' pages subcategories = self.cat.s...
+ "\s*(?:<script[^<>]+>[^<>]+<[^<>]+script>)?[^+<a href=.+?>(?P<key>.+?)<\/a><br \/>\n"
+ "\s*<a href=.+?>(?P<key>.+?)<\/a><br \/>\n"
def refresh_messages(site = None): site = site or wikipedia.getSite() # get 'all messages' special page's path path = site.allmessages_address() print 'Retrieving MediaWiki messages for %s' % repr(site) wikipedia.put_throttle() # It actually is a get, but a heavy one. allmessages = site.getUrl(path) print 'Parsing Med...
print "Search string is:\n",textsearch print "Replace string is:\n",textsubst
def parseFile(filename):
print newtext
def parseFile(filename):
return Page(self.site(), self.site().namespace(ns - 1) + ':' + self.titleWithoutNamespace())
if self.namespace() == 1: return Page(self.site(), self.titleWithoutNamespace()) else: return Page(self.site(), self.site().namespace(ns - 1) + ':' + self.titleWithoutNamespace())
def switchTalkPage(self): """ If self is a talk page, returns the associated content page; otherwise, returns the associated talk page. Returns None if self is a special page. """ ns = self.namespace() if ns < 0: # Special page return None if self.isTalkPage(): return Page(self.site(), self.site().namespace(ns - 1) + '...
if self.primaryIgnoreManager.isIgnored(refpl2):
if not self.primaryIgnoreManager.isIgnored(refpl2):
def treat(self, refpl, disambPl): """ Parameters: disambPl - The disambiguation page or redirect we don't want anything to link on refpl - A page linking to disambPl Returns False if the user pressed q to completely quit the program. Otherwise, returns True. """ if self.mylang in link_trail: linktrail=link_trail[self.m...
if not self.treat(refpl2, disambPl):
if not self.treat(refpl2, refpl):
def treat(self, refpl, disambPl): """ Parameters: disambPl - The disambiguation page or redirect we don't want anything to link on refpl - A page linking to disambPl Returns False if the user pressed q to completely quit the program. Otherwise, returns True. """ if self.mylang in link_trail: linktrail=link_trail[self.m...
wikipedia.output(u'Skiping: %s is auto entry %s(%s)' % (page,dictName,year))
wikipedia.output(u'Skiping: %s is auto entry %s(%s)' % (page.title(),dictName,year))
def generateMore(self, number): """Generate more subjects. This is called internally when the list of subjects becomes too small, but only if there is a PageGenerator""" fs = self.firstSubject() if fs: wikipedia.output(u"NOTE: The first unfinished subject is " + fs.pl().aslink(forceInterwiki = True)) print "NOTE: Numbe...
'ro': (LINKS, u"Wikipedia:Articole de calitate"),
'ro': (LINKS, u"Wikipedia:Articole fructuoase"),
def LINKS(site,name, ignore=[]): p=wikipedia.Page(site, name) links=p.linkedPages() for n in links[:]: if n.titleWithoutNamespace() in ignore: links.remove(n) links.sort() return links
'he' : [u'disambiguationafter', u'פירושונים'],
'he' : [u'disambiguationAfter', u'פירושונים'],
def __init__(self):
'sr': [u'СТРАНИЦА']
'sr': [u'СТРАНИЦА'],
def category_namespaces(self, code): namespaces = [] namespace_title = self.namespace(code, 14) namespaces.append(namespace_title) if namespace_title != namespace_title.lower(): namespaces.append(namespace_title.lower()) default_namespace_title = self.namespace('_default', 14) if namespace_title != default_namespace_ti...
'ru': [u'НАЗВАНИЕСТРАНИЦЫ2']
'ru': [u'НАЗВАНИЕСТРАНИЦЫ2'],
def category_namespaces(self, code): namespaces = [] namespace_title = self.namespace(code, 14) namespaces.append(namespace_title) if namespace_title != namespace_title.lower(): namespaces.append(namespace_title.lower()) default_namespace_title = self.namespace('_default', 14) if namespace_title != default_namespace_ti...
def change_category(article, old_cat, new_cat):
def change_category(article, old_cat_title, new_cat_title):
def add_category(sort_by_last_name = False): print "This bot has two modes: you can add a category link to all" print "pages mentioned in a List that is now in another wikipedia page" print "or you can add a category link to all pages that link to a" print "specific page. If you want the second, please give an empty" p...
cats.remove(old_cat) if new_cat != None:
sort_key = '' for cat in cats: ns = wikipedia.family.category_namespaces(wikipedia.mylang)[0].encode(wikipedia.code2encoding(wikipedia.mylang)) if cat.linkname() == ns + ':' + old_cat_title: cats.remove(cat) elif cat.linkname().startswith(ns + ':' + old_cat_title + '|'): sort_key = cat.linkname().split('|', 1)[1] ca...
def change_category(article, old_cat, new_cat): cats = article.categories() cats.remove(old_cat) if new_cat != None: cats.append(new_cat) text = article.get() text = wikipedia.replaceCategoryLinks(text, cats) article.put(text)
old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title)
old_cat_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_cat_title) new_cat_title = wikipedia.input('Please enter the new name of the category: ')
def rename_category(): old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title) # get edit summary message wikipedia.setAction(msg_change[wikipedia.choose...
wikipedia.setAction(msg_change[wikipedia.chooselang(wikipedia.mylang,msg_change)] % old_title)
wikipedia.setAction(msg_change[wikipedia.chooselang(wikipedia.mylang,msg_change)] % old_cat_title)
def rename_category(): old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title) # get edit summary message wikipedia.setAction(msg_change[wikipedia.choose...
print 'There are no articles in category ' + old_title
print 'There are no articles in category ' + old_cat_title
def rename_category(): old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title) # get edit summary message wikipedia.setAction(msg_change[wikipedia.choose...
change_category(article, old_cat, new_cat)
change_category(article, old_cat_title, new_cat_title)
def rename_category(): old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title) # get edit summary message wikipedia.setAction(msg_change[wikipedia.choose...
print 'There are no subcategories in category ' + old_title
print 'There are no subcategories in category ' + old_cat_title
def rename_category(): old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title) # get edit summary message wikipedia.setAction(msg_change[wikipedia.choose...
change_category(subcategory, old_cat, new_cat)
change_category(subcategory, old_cat_title, new_cat_title)
def rename_category(): old_title = wikipedia.input('Please enter the old name of the category: ') old_cat = catlib.CatLink(old_title) new_title = wikipedia.input('Please enter the new name of the category: ') new_cat = catlib.CatLink(new_title) # get edit summary message wikipedia.setAction(msg_change[wikipedia.choose...
old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title)
old_cat_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_cat_title)
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title)
wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_cat_title)
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
print 'There are no articles in category ' + old_title
print 'There are no articles in category ' + old_cat_title
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
change_category(article, old_cat, None)
change_category(article, old_cat_title, None)
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
print 'There are no subcategories in category ' + old_title
print 'There are no subcategories in category ' + old_cat_title
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
change_category(subcategory, old_cat, None)
change_category(subcategory, old_cat_title, None)
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
* every category page must contain some text; otherwise an edit box will be displayed instead of an article list, and the bot won't work
def remove_category(): old_title = wikipedia.input('Please enter the name of the category that should be removed: ') old_cat = catlib.CatLink(old_title) # get edit summary message wikipedia.setAction(msg_remove[wikipedia.chooselang(wikipedia.mylang,msg_remove)] % old_title) articles = old_cat.articles(recurse = 0) if ...
x,l=decode_func(x)
try: x,l=decode_func(x) except UnicodeError: print code,name print repr(x) raise
def getPage(code, name, do_edit=1, do_quote=1): """Get the contents of page 'name' from the 'code' language wikipedia""" host = langs[code] if host[-4:]=='.com': # Old algorithm name = re.sub('_', ' ', name) n=[] for x in name.split(): n.append(x[0].capitalize()+x[1:]) name='_'.join(n) #print name else: name = re.sub('...
if code in ['meta','eo','ja','zh','hi']:
if code in ['meta','eo','ja','zh','hi','he','hu']:
def code2encoding(code): if code=='ru': return 'iso-8859-5' if code=='pl': return 'iso-8859-2' if code in ['meta','eo','ja','zh','hi']: return 'utf-8' return 'iso-8859-1'
result=str(name.encode('latin1'))
result=str(name.encode(code2encoding(code)))
def link2url(name,code='nl',incode='nl'): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=...
result=str(name.encode('utf-8'))
try: result=str(name.encode('latin1')) except UnicodeError: result=str(name.encode('utf-8'))
def link2url(name,code='nl',incode='nl'): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=...
def newpages(number=10, onlyonce=False site=None, throttle=True):
def newpages(number=10, onlyonce=False, site=None, throttle=True):
def newpages(number=10, onlyonce=False site=None, throttle=True): """Generator which yields new articles subsequently. It starts with the article created 'number' articles ago (first argument). When these are all yielded (as PageLinks) it fetches NewPages again. If there is no new page, it blocks until there is one, sl...
if wikipedia.getSite('nn') in new or self.inpl.language() == 'nn':
if wikipedia.getSite('nn') in new or self.inpl.site().lang == 'nn':
def finish(self, sa = None): """Round up the subject, making any necessary changes. This method should be called exactly once after the todo list has gone empty.
insite.getSite()
insite = getSite()
def categoryFormat(links, insite = None): """Create a suitable string encoding all category links for a wikipedia page. 'links' should be a list of category pagelink objects. The string is formatted for inclusion in insite. """ if not links: return '' if insite is None: insite.getSite() s = [] for pl in links: s.appe...
if Site(default_code).category_on_one_line():
if insite.category_on_one_line():
def categoryFormat(links, insite = None): """Create a suitable string encoding all category links for a wikipedia page. 'links' should be a list of category pagelink objects. The string is formatted for inclusion in insite. """ if not links: return '' if insite is None: insite.getSite() s = [] for pl in links: s.appe...
wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.linkname(),dictName,year))
wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,year))
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if giv...
'exceptions': [u'Zемфира', u'KoЯn', u'Deadушки', u'ENTERМУЗЫКА', u'Юz', u'Lюк', u'Яndex'],
def SetColor(color): try: import win32console stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdout.SetConsoleTextAttribute(color) except: if color == FOREGROUND_BLUE: print '(b:' if color == FOREGROUND_GREEN: print '(g:' if color == FOREGROUND_RED: print '(r:'
'localsuspects': u'АаВЕеКкМНОоРрСсТуХх', 'latinsuspects': u'AaBEeKkMHOoPpCcTyXx',
'localsuspects': u'АаВЕеКкМНОопРрСсТуХх', 'latinsuspects': u'AaBEeKkMHOonPpCcTyXx',
def SetColor(color): try: import win32console stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdout.SetConsoleTextAttribute(color) except: if color == FOREGROUND_BLUE: print '(b:' if color == FOREGROUND_GREEN: print '(g:' if color == FOREGROUND_RED: print '(r:'
'exceptions': [],
def SetColor(color): try: import win32console stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdout.SetConsoleTextAttribute(color) except: if color == FOREGROUND_BLUE: print '(b:' if color == FOREGROUND_GREEN: print '(g:' if color == FOREGROUND_RED: print '(r:'
'localsuspects': u'АаВЕеІіКкМНОоРрСсТУуХх', 'latinsuspects': u'AaBEeIiKkMHOoPpCcTYyXx',
'localsuspects': u'АаВЕеІіКкМНОопРрСсТУуХх', 'latinsuspects': u'AaBEeIiKkMHOonPpCcTYyXx',
def SetColor(color): try: import win32console stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdout.SetConsoleTextAttribute(color) except: if color == FOREGROUND_BLUE: print '(b:' if color == FOREGROUND_GREEN: print '(g:' if color == FOREGROUND_RED: print '(r:'
'localsuspects': u'АаВЕеКкМНОоРрСсТуХх', 'latinsuspects': u'AaBEeKkMHOoPpCcTyXx',
'localsuspects': u'АаВЕеКкМНОопРрСсТуХх', 'latinsuspects': u'AaBEeKkMHOonPpCcTyXx', }, 'be': { 'alphabet' : u'АаБбВвГ㥴ДдЖжЗзЕеЁёЖжЗзІіЙйКкЛлМмНнОоПпРрСсТтУуЎўФфХхЦцЧчШшЫыЬьЭэЮюЯя', 'localsuspects': u'АаВЕеІіКкМНОопРрСсТуХх', 'latinsuspects': u'AaBEeIiKkMHOonPpCcTyXx',
def SetColor(color): try: import win32console stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdout.SetConsoleTextAttribute(color) except: if color == FOREGROUND_BLUE: print '(b:' if color == FOREGROUND_GREEN: print '(g:' if color == FOREGROUND_RED: print '(r:'
namespaces = [0, 10, 12, 14]
namespaces = []
def SetColor(color): try: import win32console stdout=win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE) stdout.SetConsoleTextAttribute(color) except: if color == FOREGROUND_BLUE: print '(b:' if color == FOREGROUND_GREEN: print '(g:' if color == FOREGROUND_RED: print '(r:'
if arg.startswith('-from:'): self.apfrom = arg[6:] elif arg.startswith('-from'): self.apfrom = wikipedia.input(u'Which page to start from: ')
if arg.startswith('-from'): if arg.startswith('-from:'): self.apfrom = arg[6:] else: self.apfrom = wikipedia.input(u'Which page to start from: ')
def __init__(self, args): for arg in args: arg = wikipedia.argHandler(arg, 'casechecker') if arg: if arg.startswith('-from:'): self.apfrom = arg[6:] elif arg.startswith('-from'): self.apfrom = wikipedia.input(u'Which page to start from: ') elif arg.startswith('-reqsize:'): self.aplimit = int(arg[9:]) elif arg == '-lin...
elif arg.startswith('-namespace:'): self.namespaces = [int(arg[11:])]
elif arg.startswith('-ns:'): self.namespaces.append( int(arg[4:]) )
def __init__(self, args): for arg in args: arg = wikipedia.argHandler(arg, 'casechecker') if arg: if arg.startswith('-from:'): self.apfrom = arg[6:] elif arg.startswith('-from'): self.apfrom = wikipedia.input(u'Which page to start from: ') elif arg.startswith('-reqsize:'): self.aplimit = int(arg[9:]) elif arg == '-lin...
self.params['what'] += '|links';
self.params['what'] += '|links|categories';
def __init__(self, args): for arg in args: arg = wikipedia.argHandler(arg, 'casechecker') if arg: if arg.startswith('-from:'): self.apfrom = arg[6:] elif arg.startswith('-from'): self.apfrom = wikipedia.input(u'Which page to start from: ') elif arg.startswith('-reqsize:'): self.aplimit = int(arg[9:]) elif arg == '-lin...
self.knownWords = set(l['exceptions'])
def __init__(self, args): for arg in args: arg = wikipedia.argHandler(arg, 'casechecker') if arg: if arg.startswith('-from:'): self.apfrom = arg[6:] elif arg.startswith('-from'): self.apfrom = wikipedia.input(u'Which page to start from: ') elif arg.startswith('-reqsize:'): self.aplimit = int(arg[9:]) elif arg == '-lin...
self.apfrom = self.apfrom
def Run(self): try: count = 0 for namespace in self.namespaces: self.params['apnamespace'] = namespace self.apfrom = self.apfrom title = None while True: # Get data self.params['apfrom'] = self.apfrom data = query.GetData(self.site.lang, self.params, self.verbose) try: self.apfrom = data['query']['allpages']['next'] e...
changed = False if self.replace and namespace != 14: newTitle = self.PickTarget(False, title, err[1]) if newTitle: src = wikipedia.Page(self.site, title) src.move( newTitle, u'mixed case rename') changed = True if not changed: self.WikiLog(u"* " + err[0]) printed = True
if page['ns'] == 14: self.WikiLog(u"* Move category content: " + err[0]) else: changed = False if self.replace: newTitle = self.PickTarget(False, title, err[1]) if newTitle: src = wikipedia.Page(self.site, title) src.move( newTitle, u'mixed case rename') changed = True if not changed: self.WikiLog(u"* " + err[0]) prin...
def Run(self): try: count = 0 for namespace in self.namespaces: self.params['apnamespace'] = namespace self.apfrom = self.apfrom title = None while True: # Get data self.params['apfrom'] = self.apfrom data = query.GetData(self.site.lang, self.params, self.verbose) try: self.apfrom = data['query']['allpages']['next'] e...
for l in page['links']:
for l in allLinks:
def Run(self): try: count = 0 for namespace in self.namespaces: self.params['apnamespace'] = namespace self.apfrom = self.apfrom title = None while True: # Get data self.params['apfrom'] = self.apfrom data = query.GetData(self.site.lang, self.params, self.verbose) try: self.apfrom = data['query']['allpages']['next'] e...
pageTxt = pageTxt.replace(ltxt, newTitle) pageTxt = pageTxt.replace(ltxt[0].lower() + ltxt[1:], newTitle[0].lower() + newTitle[1:]) pageTxt = pageTxt.replace(ltxt.replace(u' ', '_'), newTitle)
frmParts = self.wordBreaker.split(ltxt) toParts = self.wordBreaker.split(newTitle) if len(frmParts) != len(toParts): raise u'Splitting parts do not match counts' for i in range(0, len(frmParts)): if len(frmParts[i]) != len(toParts[i]): raise u'Splitting parts do not match word length' if len(frmParts[i]) > 0: pageTxt =...
def Run(self): try: count = 0 for namespace in self.namespaces: self.params['apnamespace'] = namespace self.apfrom = self.apfrom title = None while True: # Get data self.params['apfrom'] = self.apfrom data = query.GetData(self.site.lang, self.params, self.verbose) try: self.apfrom = data['query']['allpages']['next'] e...
self.WikiLog(u"* Error: Text replacement failed in [[:%s]] (%s)" % (title, u', '.join(msg)))
self.WikiLog(u"* Error: Text replacement failed in [[:%s]] (%s)" % (title, coloredMsg))
def Run(self): try: count = 0 for namespace in self.namespaces: self.params['apnamespace'] = namespace self.apfrom = self.apfrom title = None while True: # Get data self.params['apfrom'] = self.apfrom data = query.GetData(self.site.lang, self.params, self.verbose) try: self.apfrom = data['query']['allpages']['next'] e...
self.WikiLog(u"* Error: Could not save updated page [[:%s]] (%s)" % (title, u', '.join(msg)))
self.WikiLog(u"* Error: Could not save updated page [[:%s]] (%s)" % (title, coloredMsg))
def Run(self): try: count = 0 for namespace in self.namespaces: self.params['apnamespace'] = namespace self.apfrom = self.apfrom title = None while True: # Get data self.params['apfrom'] = self.apfrom data = query.GetData(self.site.lang, self.params, self.verbose) try: self.apfrom = data['query']['allpages']['next'] e...
reptxt = new_page_title
newlink = "[[%s]]" % new_page_title
def treat(refpl, thispl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: pass else: n = 0 curpos = 0 while 1: m=linkR.search(reftxt, pos = curpos) if not m: if n == 0: print "Not found in %s"%refpl elif not debug: refpl.put(reftxt) return True # Make sure that next time around we will not find this same hit. ...
substring. which matches the exception. Otherwise it returns None.
substring which matches the exception. Otherwise it returns None.
def checkExceptions(self, original_text): """ If one of the exceptions applies for the given text, returns the substring. which matches the exception. Otherwise it returns None. """ for exception in self.exceptions: if self.regex: exception = re.compile(exception, re.UNICODE) hit = exception.search(original_text) if hi...
def allowedbot(site):
def allowedbot(username, site):
def allowedbot(site): """Checks whether the bot is listed on Wikipedia:bots""" pl = wikipedia.PageLink(site, "Wikipedia:Bots") text = pl.get() return "[[User:%s" % username in text
return "[[User:%s" % username in text
return "[[user:%s" % username in text.lower()
def allowedbot(site): """Checks whether the bot is listed on Wikipedia:bots""" pl = wikipedia.PageLink(site, "Wikipedia:Bots") text = pl.get() return "[[User:%s" % username in text
if not allowedbot(ensite):
if not allowedbot(username, ensite):
def main(args): username = password = None for arg in args:#sys.argv[1:]: arg = wikipedia.argHandler(arg) if arg is None: continue if arg.startswith("-user:"): username = arg[6:] elif arg.startswith("-pass:"): # not recommended password = arg[6:] else: sys.exit("Unknown argument: %s" % arg) mysite = wikipedia.getSite...
if namespace == -1 or namespace != entry.namespace :
if namespace != -1 and namespace != entry.namespace:
def read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex, namespace): ''' Generator which will yield PageLinks to pages that might contain text to replace. These pages will be retrieved from a local sql dump file (cur table). Arguments: * sqlfilename - the dump's path, either absolute or relative * r...
lineR = re.compile('<li> \(.+?\) \(.+?\) <a href=".+?" title=".+?">(?P<datetime>.+?)</a> . . <a href=".+?" title=".+?">(?P<username>.+?)</a> \(<a href=".+?" title=".+?">.+?</a>\) . . (?P<resolution>\d+.+?\d+) \((?P<size>\d+) .+?\)( <span class=\'comment\'>(?P<comment>.*?)</span>)?</li>')
lineR = re.compile('<li> \(.+?\) \(.+?\) <a href=".+?" title=".+?">(?P<datetime>.+?)</a> . . <a href=".+?" title=".+?">(?P<username>.+?)</a> \(<a href=".+?" title=".+?">.+?</a>\) . . (?P<resolution>\d+.+?\d+) \((?P<size>[\d,]+) .+?\)( <span class="comment">(?P<comment>.*?)</span>)?</li>')
def getFileVersionHistory(self): result = [] history = re.search('(?s)<ul class="special">.+?</ul>', self.getImagePageContents()).group() lineR = re.compile('<li> \(.+?\) \(.+?\) <a href=".+?" title=".+?">(?P<datetime>.+?)</a> . . <a href=".+?" title=".+?">(?P<username>.+?)</a> \(<a href=".+?" title=".+?">.+?</a>\) . ....
pl3 = wikipedia.Page(pl.site(),arg.args[0]) wikipedia.output(u"NOTE: %s is redirect to %s" % (pl.aslink(forceInterwiki = True), pl3.aslink(forceInterwiki = True))) if pl == self.inpl: isredirect = 1 for pl2 in self.todo: counter.minus(pl2.site()) self.todo = {} pass elif not globalvar.followredirect: print "NOTE: no...
try: pl3 = wikipedia.Page(pl.site(),arg.args[0]) wikipedia.output(u"NOTE: %s is redirect to %s" % (pl.aslink(forceInterwiki = True), pl3.aslink(forceInterwiki = True))) if pl == self.inpl: isredirect = 1 for pl2 in self.todo: counter.minus(pl2.site()) self.todo = {} pass elif not globalvar.followredirect: print "NOT...
def workDone(self, counter): """This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo.""" # Loop over all the pages that should have been taken care of ...
first = first.lower()
first = first.lower().strip()
def isInterwikiLink(self, s): """ Try to check whether s is in the form "foo:bar" or ":foo:bar" where foo is a known language code or family. In such a case we are dealing with an interwiki link. """ s = s.lstrip(":") if not ':' in s: return False first, rest = s.split(':',1) # interwiki codes are case-insensitive firs...
return False
return self.isInterwikiLink(rest)
def isInterwikiLink(self, s): """ Try to check whether s is in the form "foo:bar" or ":foo:bar" where foo is a known language code or family. In such a case we are dealing with an interwiki link. """ s = s.lstrip(":") if not ':' in s: return False first, rest = s.split(':',1) # interwiki codes are case-insensitive firs...
data = {"wpName": self.username,
data = {"wpName": self.username.encode(self.site.encoding()),
def getCookie(self, remember=True): """Login to wikipedia. remember Remember login (default: True) Returns cookie data if succesful, None otherwise.""" data = {"wpName": self.username, "wpPassword": self.password, "wpLoginattempt": "Aanmelden & Inschrijven", # dutch button label seems to work for all wikis "wpRem...
fam Wikimedia family (optional: defaults to configured)
fam Wikimedia family (optional: defaults to configured). Can either be a string or a Family object.
def __init__(self, code, fam=None, user=None): """Constructor takes three arguments:
family = Family(fam) if code in family.obsolete and family.obsolete[code]: code = family.obsolete[code]
def getSite(code = None, fam = None, user=None): if code == None: code = default_code if fam == None: fam = default_family # if we got an outdated code, use the new one instead. family = Family(fam) if code in family.obsolete and family.obsolete[code]: code = family.obsolete[code] key = '%s:%s'%(fam,code) if not _sites...
self.problem(u"%s: %s gives duplicate interwiki on same site %s" % (self.originPage.aslink(), page.aslink(True), linkedPage.aslink(True))) if globalvar.autonomous: self.todo = [] return
wikipedia.output(u"NOTE: %s: %s gives duplicate interwiki on same site %s" % (self.originPage.aslink(), page.aslink(True), linkedPage.aslink(True)))
def workDone(self, counter): """ This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo. """ # Loop over all the pages that should have been taken care o...
print "The specified page is not a redirect." sys.exit(1)
print "The specified page is not a redirect. Skipping." continue
def run(self): if self.main_only: if ignore_title.has_key(self.mylang): ignore_title[self.mylang] += self.mysite.namespaces() else: ignore_title[self.mylang] = self.mysite.namespaces() for disambTitle in self.page_list: # when run with -redir argument, there's another summary message if self.solve_redirect: wikipedia....
replacements.append((templateR, '{{subst:' + self.old + '}}'))
replacements.append((templateR, '{{subst:' + self.old + '\g<parameters>}}'))
def run(self): # regular expression to find the original template. # {{msg:vfd}} does the same thing as {{msg:Vfd}}, so both will be found. # The new syntax, {{vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapit...
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(),msg_change) % oldCatTitle)
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(),msg_change) % oldCat.title())
def __init__(self, oldCatTitle, newCatTitle): self.oldCat = catlib.Category(wikipedia.getSite(), 'Category:' + oldCatTitle) self.newCatTitle = newCatTitle # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(),msg_change) % oldCatTitle)
def read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex):
def read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex, namespace):
def read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex): ''' Generator which will yield PageLinks to pages that might contain text to replace. These pages will be retrieved from a local sql dump file (cur table). Arguments: * sqlfilename - the dump's path, either absolute or relative * replacements...
for exception in exceptions: if regex: exception = re.compile(exception) if exception.search(entry.text): skip_page = True break else: if entry.text.find(exception) != -1: skip_page = True break
if namespace == -1 or namespace != entry.namespace : continue else: for exception in exceptions: if regex: exception = re.compile(exception) if exception.search(entry.text): skip_page = True break else: if entry.text.find(exception) != -1: skip_page = True break
def read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex): ''' Generator which will yield PageLinks to pages that might contain text to replace. These pages will be retrieved from a local sql dump file (cur table). Arguments: * sqlfilename - the dump's path, either absolute or relative * replacements...
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None):
def generator(source, replacements, exceptions, regex, namespace, textfilename = None, sqlfilename = None, pagenames = None):
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ...
for pl in read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex):
for pl in read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex, namespace):
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ...
namespace = -1
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ...
wikipedia.setAction(wikipedia.translate(wikipedia.mylang, msg)+change)
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ...
for pl in generator(source, replacements, exceptions, regex, textfilename, sqlfilename, pagenames):
for pl in generator(source, replacements, exceptions, regex, namespace, textfilename, sqlfilename, pagenames):
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ...
print 'No changes were necessary in %s' % pl.linkname()
try: print 'No changes were necessary in %s' % pl.linkname() except UnicodeEncodeError: print 'Error decoding pl.linkname()' continue
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagenames = None): ''' Generator which will yield PageLinks for pages that might contain text to replace. These pages might be retrieved from a local SQL dump file or a text file, or as a list of pages entered by the user. ...
def resolveRedirect(self):
def resolveRedirect(self, useHEAD = True):
def resolveRedirect(self): ''' Requests the header from the server. If the page is an HTTP redirect, returns the redirect target URL as a string. Otherwise returns None. ''' if self.scheme == 'http': conn = httplib.HTTPConnection(self.host) elif self.scheme == 'https': conn = httplib.HTTPSConnection(self.host) conn.req...
conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse()
try: if useHEAD: conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) else: conn.request('GET', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse() except httplib.BadStatusLine: return self.resolveRedirect(useHEAD = False)
def resolveRedirect(self): ''' Requests the header from the server. If the page is an HTTP redirect, returns the redirect target URL as a string. Otherwise returns None. ''' if self.scheme == 'http': conn = httplib.HTTPConnection(self.host) elif self.scheme == 'https': conn = httplib.HTTPSConnection(self.host) conn.req...
choice = wikipedia.input('WARNING: %s is a disambiguation page, but %s doesn\'t seem to be one. Follow it anyway? [y|N]' % (self.inpl.aslink(), pl.aslink()))
choice = wikipedia.inputChoice('WARNING: %s is a disambiguation page, but %s doesn\'t seem to be one. Follow it anyway?' % (self.inpl.aslink(), pl.aslink()), ['Yes', 'No'], ['y', 'N'], 'N')
def workDone(self, counter): """This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo.""" # Loop over all the pages that should have been taken care of ...