rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
for c in 'C','G','H','J','S','U':
for c in 'CGHJSU':
def run(self): dt=15 while 1: try: data = self.getData() except socket.error: # Print the traceback of the caught exception print ''.join(traceback.format_exception(*sys.exc_info())) output(u'DBG> got socket error in GetAll.run. Sleeping for %d seconds'%dt) time.sleep(dt) dt *= 2 else: break handler = WikimediaXmlHandl...
for x in 'X','x':
for x in 'Xx':
def run(self): dt=15 while 1: try: data = self.getData() except socket.error: # Print the traceback of the caught exception print ''.join(traceback.format_exception(*sys.exc_info())) output(u'DBG> got socket error in GetAll.run. Sleeping for %d seconds'%dt) time.sleep(dt) dt *= 2 else: break handler = WikimediaXmlHandl...
self.get(force = True)
try: self.get(force = True) except (NoPage, IsRedirectPage, LockedPage): pass
def put(self, newtext, comment=None, watchArticle = False, minorEdit = True): """Replace the new page with the contents of the first argument. The second argument is a string that is to be used as the summary for the modification """ if self.exists(): newPage="0" else: newPage="1" if self.site().version() >= "1.4": if ...
R = re.compile(r"\<input type='hidden' value=\"(.*?)\" name=\"wpEditToken\"") tokenloc = R.search(text) if tokenloc: site.puttoken(tokenloc.group(1)) elif not site.gettoken(): site.puttoken('')
def getPage(site, name, get_edit_page = True, read_only = False, do_quote = True, get_redirect=False, throttle = True): """ Get the contents of page 'name' from the 'site' wiki Do not use this directly; for 99% of the possible ideas you can use the PageLink object instead. Arguments: site - the wiki site name...
R = re.compile(r"\<input type='hidden' value=\"(.*?)\" name=\"wpEditToken\"") tokenloc = R.search(text) if tokenloc: site.puttoken(tokenloc.group(1)) elif not site.gettoken(): site.puttoken('')
def getPage(site, name, get_edit_page = True, read_only = False, do_quote = True, get_redirect=False, throttle = True): """ Get the contents of page 'name' from the 'site' wiki Do not use this directly; for 99% of the possible ideas you can use the PageLink object instead. Arguments: site - the wiki site name...
try: if not site.nocapitalize: title = title[0].upper() + title[1:] except IndexError: pass
def __init__(self, site, title = None, insite = None, tosite = None): """ Constructor. Normally called with two arguments: Parameters: 1) The wikimedia site on which the page resides 2) The title of the page as a unicode string The argument insite can be specified to help decode the name; it is the wikimedia site wher...
global loggedin if "Userlogin" in text: loggedin = False else: loggedin = True
if code == mylang: global loggedin if "Userlogin" in text: loggedin = False else: loggedin = True
def getPage(code, name, do_edit = 1, do_quote = 1): """Get the contents of page 'name' from the 'code' language wikipedia Do not use this directly; use the PageLink object instead.""" host = langs[code] if code in oldsoftware: # Old algorithm name = re.sub('_', ' ', name) n = [] for x in name.split(): n.append(x[0].cap...
sa.add(wikipedia.PageLink(wikipedia.mylang, (date.date_format[startmonth][wikipedia.mylang]) % day))
sa.add(wikipedia.PageLink(wikipedia.mylang, (date.date_format[month][wikipedia.mylang]) % day))
def ReadWarnfile(fn, sa): import re R=re.compile(r'WARNING: ([^\[]*):\[\[([^\[]+)\]\]([^\[]+)\[\[([^\[]+):([^\[]+)\]\]') f=open(fn) hints={} for line in f.readlines(): m=R.search(line) if m: #print "DBG>",line if m.group(1)==wikipedia.mylang: #print m.group(1), m.group(2), m.group(3), m.group(4), m.group(5) if not hint...
def __init__(self, url, redirectList = []): """ redirectList is a list of redirects which were resolved by
def __init__(self, url, redirectChain = []): """ redirectChain is a list of redirects which were resolved by
def __init__(self, url, redirectList = []): """ redirectList is a list of redirects which were resolved by resolveRedirect(). This is needed to detect redirect loops. """ self.url = url self.redirectList = redirectList # we ignore the fragment self.scheme, self.host, self.path, self.query, self.fragment = urlparse.urls...
self.redirectList = redirectList
self.redirectChain = redirectChain + [self.url]
def __init__(self, url, redirectList = []): """ redirectList is a list of redirects which were resolved by resolveRedirect(). This is needed to detect redirect loops. """ self.url = url self.redirectList = redirectList # we ignore the fragment self.scheme, self.host, self.path, self.query, self.fragment = urlparse.urls...
if redirTarget.startswith('http://'):
if redirTarget.startswith('http://') or redirTarget.startswith('https://'):
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. ''' conn = httplib.HTTPConnection(self.host) conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse()
newURL = 'http://%s%s' % (self.host, redirTarget)
newURL = '%s://%s%s' % (self.protocol, self.host, redirTarget)
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. ''' conn = httplib.HTTPConnection(self.host) conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse()
newURL = 'http://%s/%s' % (self.host, redirTarget)
newURL = '%s://%s/%s' % (self.protocol, self.host, redirTarget)
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. ''' conn = httplib.HTTPConnection(self.host) conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse()
Otherwise returns false and an error message.
Otherwise returns false
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false and an error message. """ try: url = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncod...
if url in self.redirectList: self.redirectList.append(url) return False, u'HTTP Redirect Loop: %s' % ' -> '.join(self.redirectList)
if url in self.redirectChain: return False, u'HTTP Redirect Loop: %s' % ' -> '.join(self.redirectChain + [url])
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false and an error message. """ try: url = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncod...
self.redirectList.append(url) redirChecker = LinkChecker(url, self.redirectList)
redirChecker = LinkChecker(url, self.redirectChain)
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false and an error message. """ try: url = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncod...
linkR = re.compile(r'http://[^\]\s]*[^\]\)\s]')
linkR = re.compile(r'http[s]?://[^\]\s]*[^\]\)\s]')
def checkLinksIn(self, title, text): # RFC 2396 says that URLs may only contain certain characters. # For this regex we also accept non-allowed characters, so that the bot # will later show these links as broken ('Non-ASCII Characters in URL'). # Note: while allowing parenthesis inside URLs, MediaWiki will regard # rig...
while threading.activeCount() > 1 and i < 10:
while threading.activeCount() > 1 and i < 30:
def main(): start = '!' source = None sqlfilename = None pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, logname = 'weblinkchecker.log') if arg: if arg.startswith('-sql'): if len(arg) == 4: sqlfilename = wikipedia.input(u'Please enter the SQL dump\'s filename: ') else: sqlfilename = arg[5:] sour...
def Movepages(page):
def Movepages(page, deletedPages):
def Movepages(page): pagetitle = page.title() wikipedia.output(u'\n>>>> %s <<<<' % pagetitle) ask = wikipedia.input('What do you do: (c)hange page name, (n)ext page or (q)uit?') if ask == 'c': pagemove = wikipedia.input(u'New page name:') titleroot = wikipedia.Page(wikipedia.getSite(), pagetitle) msg = wikipedia.transl...
pagedel = wikipedia.Page(wikipedia.getSite(), pagetitle) pagedel.delete(pagetitle)
if deletedPages == True: pagedel = wikipedia.Page(wikipedia.getSite(), pagetitle) pagedel.delete(pagetitle) wikipedia.output('Page %s deleted successful.' % pagetitle)
def Movepages(page): pagetitle = page.title() wikipedia.output(u'\n>>>> %s <<<<' % pagetitle) ask = wikipedia.input('What do you do: (c)hange page name, (n)ext page or (q)uit?') if ask == 'c': pagemove = wikipedia.input(u'New page name:') titleroot = wikipedia.Page(wikipedia.getSite(), pagetitle) msg = wikipedia.transl...
for page in generator: Movepages(page)
for page in generator: Movepages(page, deletedPages)
def main(): categoryName = None singlePageTitle = [] referredPageTitle = None for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'movepages') if arg: if arg.startswith('-cat'): if len(arg) == 4: categoryName = wikipedia.input(u'Enter the category name:') else: categoryName = arg[5:] elif arg.startswith('-ref'): ...
for page in generator: Movepages(page)
for page in generator: Movepages(page, deletedPages) elif prefixPageTitle: categoryName = wikipedia.input('Category:') cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % categoryName) gen = pagegenerators.CategorizedPageGenerator(cat) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for pag...
def main(): categoryName = None singlePageTitle = [] referredPageTitle = None for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'movepages') if arg: if arg.startswith('-cat'): if len(arg) == 4: categoryName = wikipedia.input(u'Enter the category name:') else: categoryName = arg[5:] elif arg.startswith('-ref'): ...
Movepages(singlePage)
Movepages(singlePage, deletedPages)
def main(): categoryName = None singlePageTitle = [] referredPageTitle = None for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'movepages') if arg: if arg.startswith('-cat'): if len(arg) == 4: categoryName = wikipedia.input(u'Enter the category name:') else: categoryName = arg[5:] elif arg.startswith('-ref'): ...
newcat = newcat.encode(wikipedia.code2encoding(wikipedia.mylang))
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...
if self.replaceLinks(page, new, sa): updatedSites.append(site) else:
try: if self.replaceLinks(page, new, sa): updatedSites.append(site) except LinkMustBeRemoved:
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.
else: raise LinkMustBeRemoved('Found incorrect link to %s in %s'% (",".join([x.lang for x in removing]), pl.aslink(forceInterwiki = True)))
def replaceLinks(self, pl, new, sa): """ Returns True if saving was successful. """ if pl.title() != pl.sectionFreeTitle(): # This is not a page, but a subpage. Do not edit it. wikipedia.output(u"Not editing %s: not doing interwiki on subpages" % pl.aslink(forceInterwiki = True)) return False wikipedia.output(u"Updatin...
wikipedia.output(u"NOTE: ignoring %s and its interwiki links" % pl.aslink(forceInterwiki = True))
wikipedia.output(u"NOTE: ignoring %s and its interwiki links" % page2.aslink(forceInterwiki = 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 of ...
if len(self.done) == 1 and len(self.todo) == 0 and isredirect == 0:
if len(self.done) == 1 and len(self.todo) == 0 and isredirect == 0 and self.inpl.exists():
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 ...
for lang in self.firstSubject().openCodes():
oc = self.firstSubject().openCodes() if wikipedia.mylang in oc: return wikipedia.mylang for lang in oc:
def maxOpenCode(self): """Return the code of the foreign language that has the most open queries plus the number. If there is nothing left, return None, 0. Only languages that are TODO for the first Subject are returned.""" max = 0 maxlang = None
return maxlang, max
return maxlang
def maxOpenCode(self): """Return the code of the foreign language that has the most open queries plus the number. If there is nothing left, return None, 0. Only languages that are TODO for the first Subject are returned.""" max = 0 maxlang = None
maxlang, max = self.maxOpenCode() return maxlang
return self.maxOpenCode()
def selectQueryCode(self): """Select the language code the next query should go out for.""" # How many home-language queries we still have? mycount = self.counts.get(wikipedia.mylang,0) # Do we still have enough subjects to work on for which the # home language has been retrieved? This is rough, because # some subjects...
raise AssertionError("Invalid pattern %s: Zero padding size is not yet implemented!" % pattern)
def escapePattern2( pattern ): """Converts a string pattern into a regex expression and cache. Allows matching of any _digitDecoders inside the string. Returns a compiled regex object and a list of digit decoders""" if pattern not in _escPtrnCache2: newPattern = u'^' # begining of the string strPattern = u'' decoders ...
params = [ decoders[i][1](params[i]) for i in range(len(params)) ]
params = [ MakeParameter(decoders[i], params[i]) for i in range(len(params)) ]
def dh( value, pattern, encf, decf, filter = None ): """This function helps in year parsing. Usually it will be used as a lambda call in a map: lambda v: dh( v, u'pattern string', encodingFunc, decodingFunc ) encodingFunc: Converts from an integer parameter to another integer or a tuple of integers. Depending on the p...
raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders)))
raise AssertionError("A single parameter does not match %d decoders." % len(decoders))
def dh( value, pattern, encf, decf, filter = None ): """This function helps in year parsing. Usually it will be used as a lambda call in a map: lambda v: dh( v, u'pattern string', encodingFunc, decodingFunc ) encodingFunc: Converts from an integer parameter to another integer or a tuple of integers. Depending on the p...
params = decoders[0][1](params) return strPattern % params
return strPattern % MakeParameter(decoders[0], params) def MakeParameter( decoder, param ): newValue = decoder[1](param) if len(decoder) == 4 and len(newValue) < decoder[3]: newValue = decoder[0][0] * (decoder[3]-len(newValue)) + newValue return newValue
def dh( value, pattern, encf, decf, filter = None ): """This function helps in year parsing. Usually it will be used as a lambda call in a map: lambda v: dh( v, u'pattern string', encodingFunc, decodingFunc ) encodingFunc: Converts from an integer parameter to another integer or a tuple of integers. Depending on the p...
'ur' : lambda m: multi( m, [ (lambda v: dh_centuryAD( v, u'0%d00صبم' ), lambda p: p < 10), (lambda v: dh_centuryAD( v, u'%d00صبم' ), alwaysTrue)]),
'ur' : lambda v: dh_centuryAD( v, u'%2d00صبم' ),
def dh( value, pattern, encf, decf, filter = None ): """This function helps in year parsing. Usually it will be used as a lambda call in a map: lambda v: dh( v, u'pattern string', encodingFunc, decodingFunc ) encodingFunc: Converts from an integer parameter to another integer or a tuple of integers. Depending on the p...
return
return True
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 # Make sure that next time around we will not find this same hit. curpo...
wikipedia.setAction(wikipedia.translate(wikipedia.mylang, msg )+ ' (-' + commandline_replacements[0] + ' +' + commandline_replacements[1] + ')')
wikipedia.setAction(wikipedia.translate(wikipedia.mylang, msg ) % ' (-' + commandline_replacements[0] + ' +' + commandline_replacements[1] + ')')
def generator(source, replacements, exceptions, regex, namespace, 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 ...
wikipedia.setAction(wikipedia.translate(wikipedia.mylang, msg)+change)
default_summary_message = wikipedia.translate(wikipedia.mylang, msg) % change wikipedia.output(u'The summary message will default to: %s' % default_summary_message) summary_message = wikipedia.input(u'Press Enter to use this default message, or enter a description of the changes your bot will make:') if summary_messag...
def generator(source, replacements, exceptions, regex, namespace, 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 ...
for title in self.catlist(recurse)[1]:
for title in self.catlist(recurse)[2]:
def supercategories(self, recurse = False): """Create a list of all subcategories of the current category.
if parts=[]:
if parts==[]:
def catname(self): """The name of the page without the namespace part. Gives an error if the page is from the main namespace.""" title=self.linkname() parts=title.split(':') parts=parts[1:] if parts=[]: raise NoNamespace(self) return ':'.join(parts)
'_default': [u'Portal', self.namespaces[100]['_default']],
'_default': u'Portal',
def __init__(self): family.Family.__init__(self) self.name = 'wikisource' for lang in self.knownlanguages: self.langs[lang] = lang+'.wikisource.org'
'_default': [u'Portal talk', self.namespaces[101]['_default']],
'_default': u'Portal talk',
def __init__(self): family.Family.__init__(self) self.name = 'wikisource' for lang in self.knownlanguages: self.langs[lang] = lang+'.wikisource.org'
'_default': [u'Author', self.namespaces[102]['_default']],
'_default': u'Author',
def __init__(self): family.Family.__init__(self) self.name = 'wikisource' for lang in self.knownlanguages: self.langs[lang] = lang+'.wikisource.org'
'_default': [u'Author talk', self.namespaces[103]['_default']],
'_default': u'Author talk',
def __init__(self): family.Family.__init__(self) self.name = 'wikisource' for lang in self.knownlanguages: self.langs[lang] = lang+'.wikisource.org'
listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage:
listpageTitle = wikipedia.input(u'Wiki page with list of pages to change:') site = wikipedia.getSite() if listpageTitle:
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
pl = wikipedia.Page(wikipedia.getSite(), listpage)
listpage = wikipedia.Page(site, listpageTitle)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.')
wikipedia.output(u'The page %s could not be loaded from the server.' % listpageTitle)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
pagenames = pl.links()
pages = [wikipedia.Page(site, title) for title in listpage.links()]
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
refpage = wikipedia.input(u'Wikipedia page that is now linked to:') page = wikipedia.Page(wikipedia.getSite(), refpage) pagenames = page.getReferences() print " ==> %d pages to process"%len(pagenames)
referredPage = wikipedia.input(u'Wikipedia page that is now linked to:') page = wikipedia.Page(wikipedia.getSite(), referredPage) pages = page.getReferences() print " ==> %d pages to process" % len(pages)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:]
newcatTitle = wikipedia.input(u'Category to add (do not give namespace):') newcatTitle = newcatTitle[:1].capitalize() + newcatTitle[1:]
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat)
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcatTitle)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm)
for page in pages:
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink()))
answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (page.aslink()))
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
cats = pl2.categories() rawcats = pl2.rawcategories()
cats = page.categories() rawcats = page.rawcategories()
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink()))
wikipedia.output(u"%s doesn't exist yet. Ignoring." % (page.linkname()))
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink()))
redirTarget = wikipedia.Page(site,arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to %s. Ignoring." % (page.linkname(), redirTarget.linkname()))
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat)
for cat in cats: wikipedia.output(u"* %s" % cat.linkname()) catpl = wikipedia.Page(site, cat_namespace + ':' + newcatTitle)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
catpl = sorted_by_last_name(catpl, pl2)
catpl = sorted_by_last_name(catpl, page)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink()))
wikipedia.output(u"%s is already in %s." % (page.linkname(), catpl.linkname()))
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
text = pl2.get()
text = page.get()
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
pl2.put(text)
page.put(text)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' 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 "spe...
interwikiR = re.compile(r'\[\[([a-z\-]+):([^\]]*)\]\]')
interwikiR = re.compile(r'\[\[([a-z\-]+):([^\[\]]*)\]\]')
def getLanguageLinks(text, insite = None): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}. Do not call this routine directly, use Page objects instead""" if insite == None: insite = getSite() result = {} # This regular expression will find every link that is possibly a...
gen = XmlDumpReplacePageGenerator(xmlfilename, replacements, exceptions)
gen = XmlDumpReplacePageGenerator(xmlFilename, replacements, exceptions)
def main(): gen = None # How we want to retrieve information on which pages need to be changed. # Can either be 'xmldump', 'textfile' or 'userinput'. source = None # Array which will collect commandline parameters. # First element is original text, second element is replacement text. commandline_replacements = [] # A l...
article = unicode(article, "utf-8") conn.request("GET", '/wiki/'+article, "", headers) response = conn.getresponse() data = response.read()
ua = article while len(data) < 2: url = '/wiki/'+ua conn.request("GET", url, "", headers) response = conn.getresponse() data = response.read() if len(data) < 2: result = R.match(response.getheader("Location", )) ua = result.group(1)
def extractArticle(data): """ takes a string with the complete HTML-file and returns the article which is contained in <div id='article'> and the pagestats which contain information on last change """ s = StringIO.StringIO(data) rPagestats = re.compile('.*(\<span id\=\'pagestats\'\>.*\<\/span\>).*') rBody = re.compil...
sourceImagePage.put(original_description + '\n\n' + nowCommonsTemplate[sourceSite.lang] % targetFilename, comment = nowCommonsMessage[sourceSite.lang])
sourceImagePage.put(description + '\n\n' + nowCommonsTemplate[sourceSite.lang] % targetFilename, comment = nowCommonsMessage[sourceSite.lang])
def transferImage(self, sourceImagePage, debug=False): """Gets a wikilink to an image, downloads it and its description, and uploads it to another wikipedia. Returns the filename which was used to upload the image This function is used by imagetransfer.py and by copy_table.py """ sourceSite = sourceImagePage.site() if ...
overwrite_articles = True
overwrite_articles = True elif arg.startswith('-help'): wikipedia.output(__doc__, 'utf-8')
def main(): mysite = wikipedia.getSite() sa = [] output_directory = "" save_images = False overwrite_images = False overwrite_articles = False for arg in sys.argv[1:]: if arg.startswith("-lang:"): lang = arg[6:] elif arg.startswith("-file:"): f=open(arg[6:], 'r') R=re.compile(r'.*\[\[([^\]]*)\]\].*') m = False for lin...
wikipedia.output(u"Skipping link %s to an ignored language"%page2)
wikipedia.output(u"Skipping link %s to an ignored language" % page2.aslink())
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 ...
wikipedia.output(u"Skipping link %s to an ignored page"%page2)
wikipedia.output(u"Skipping link %s to an ignored page" % page2.aslink())
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 ...
if "</noinclude>" in s2[firstafter:]:
if "</noinclude>" in s2[firstafter:] and firstafter < 0:
def replaceCategoryLinks(oldtext, new, site = None): """Replace the category links given in the wikitext given in oldtext by the new links given in new. 'new' should be a list of Category objects. """ if site is None: site = getSite() if site == Site('de', 'wikipedia'): raise Error('The PyWikipediaBot is no longer al...
conn.putheader('Host', host)
def post_multipart(host, selector, fields, files, cookies): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page...
def __init__(self, url, description = u'', keepFilename = False, targetSite = None, urlEncoding = None):
def __init__(self, url, description = u'', keepFilename = False, verifyDescription = True, targetSite = None, urlEncoding = None):
def __init__(self, url, description = u'', keepFilename = False, targetSite = None, urlEncoding = None): self.url = url self.urlEncoding = urlEncoding self.description = description self.keepFilename = keepFilename if config.upload_to_commons: self.targetSite = targetSite or wikipedia.getSite('commons', 'commons') else...
choice = wikipedia.inputChoice(u'Do you want to change this description?', ['Yes', 'No'], ['y', 'N'], 'n') if choice == 'y': import editarticle editor = editarticle.TextEditor() newDescription = editor.edit(self.description) if newDescription: self.description = newDescription
if self.verifyDescription: newDescription = u'' choice = wikipedia.inputChoice(u'Do you want to change this description?', ['Yes', 'No'], ['y', 'N'], 'n') if choice == 'y': import editarticle editor = editarticle.TextEditor() newDescription = editor.edit(self.description) if newDescription: self.description = newDescr...
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ # Get file contents if '://' in self...
arg = wikipedia.argHandler(arg, 'upload')
def main(args): url = u'' description = [] keepFilename = False for arg in args: arg = wikipedia.argHandler(arg, 'upload') if arg: if arg.startswith('-keep'): keepFilename = True elif url == u'': url = arg else: description.append(arg) description = u' '.join(description) bot = UploadRobot(url, description, keepFilena...
bot = UploadRobot(url, description, keepFilename)
bot = UploadRobot(url, description, keepFilename, verifyDescription)
def main(args): url = u'' description = [] keepFilename = False for arg in args: arg = wikipedia.argHandler(arg, 'upload') if arg: if arg.startswith('-keep'): keepFilename = True elif url == u'': url = arg else: description.append(arg) description = u' '.join(description) bot = UploadRobot(url, description, keepFilena...
self.linkR = re.compile(r'\[\[([^\]\|]*)(?:\|([^\]]*))?\]\](' + linktrail + ')')
self.linkR = re.compile(r'\[\[(?P<title>[^\]\|
def setupRegexes(self): # compile regular expressions self.ignore_contents_regexes = [] if self.ignore_contents.has_key(self.mylang): for ig in self.ignore_contents[self.mylang]: self.ignore_contents_regexes.append(re.compile(ig))
if wikipedia.isInterwikiLink(m.group(1)):
if wikipedia.isInterwikiLink(m.group('title')):
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. """
linkpl=wikipedia.Page(disambPl.site(), m.group(1))
linkpl=wikipedia.Page(disambPl.site(), m.group('title'))
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. """
page_title = m.group(1) link_text = m.group(2)
page_title = m.group('title') link_text = m.group('label')
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. """
trailing_chars = m.group(3)
if m.group('section') == None: section = '' else: section = m.group('section') trailing_chars = m.group('linktrail')
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 replaceit and trailing_chars: newlink = "[[%s]]%s" % (new_page_title, trailing_chars) elif new_page_title == link_text or replaceit:
if replaceit and trailing_chars: newlink = "[[%s%s]]%s" % (new_page_title, section, trailing_chars) elif replaceit or (new_page_title == link_text and not section):
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. """
elif len(new_page_title) <= len(link_text) and link_text[:len(new_page_title)] == new_page_title and re.sub(self.trailR, '', link_text[len(new_page_title):]) == '':
elif len(new_page_title) <= len(link_text) and link_text[:len(new_page_title)] == new_page_title and re.sub(self.trailR, '', link_text[len(new_page_title):]) == '' and not section:
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. """
newlink = "[[%s|%s]]" % (new_page_title, link_text)
newlink = "[[%s%s|%s]]" % (new_page_title, section, link_text)
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. """
wikipedia.output(u'Skiping: %s is in the skip list' % page)
wikipedia.output(u'Skiping: %s is in the skip list' % page.title())
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...
output(u'Getting references to %s' % self.aslink())
def getReferences(self, follow_redirects=True, withTemplateInclusion = True, onlyTemplateInclusion = False): """ Return a list of pages that link to the page. Parameters: * follow_redirects - if True, also returns pages that link to a redirect pointing to the page. * withTemplateInclusion - if True, also returns ...
isTemplateInclusion = (lmatch.group("templateInclusion") != None)
try: isTemplateInclusion = (lmatch.group("templateInclusion") != None) except IndexError: isTemplateInclusion = False
def getReferences(self, follow_redirects=True, withTemplateInclusion = True, onlyTemplateInclusion = False): """ Return a list of pages that link to the page. Parameters: * follow_redirects - if True, also returns pages that link to a redirect pointing to the page. * withTemplateInclusion - if True, also returns ...
arg = wikipedia.argHandler(arg) if arg:
if wikipedia.argHandler(arg):
def main(args): filename = '' description = [] keep = False wiki = '' for arg in args: arg = wikipedia.argHandler(arg) if arg: print arg if arg.startswith('-keep'): keep = True elif arg.startswith('-wiki:'): wiki=arg[6:] elif filename == '': filename = arg else: description.append(arg) description = ' '.join(descripti...
except:
finally:
def main(args): filename = '' description = [] keep = False wiki = '' for arg in args: arg = wikipedia.argHandler(arg) if arg: print arg if arg.startswith('-keep'): keep = True elif arg.startswith('-wiki:'): wiki=arg[6:] elif filename == '': filename = arg else: description.append(arg) description = ' '.join(descripti...
raise else: wikipedia.stopme()
def main(args): filename = '' description = [] keep = False wiki = '' for arg in args: arg = wikipedia.argHandler(arg) if arg: print arg if arg.startswith('-keep'): keep = True elif arg.startswith('-wiki:'): wiki=arg[6:] elif filename == '': filename = arg else: description.append(arg) description = ' '.join(descripti...
print "Found %d references" % len(refs)
wikipedia.output(u"Found %d references." % len(refs))
def getReferences(self): refs = wikipedia.getReferences(self.disambPl, follow_redirects = False) print "Found %d references" % len(refs) # Remove ignorables if ignore_title.has_key(self.disambPl.site().lang): ignore_title_regexes = [] for ig in ignore_title[self.disambPl.site().lang]: ig = ig.encode(wikipedia.myencodin...
wikipedia.output(u'Remaining %i thread will be killed.' % (threading.activeCount() - 2))
wikipedia.output(u'Remaining %i threads will be killed.' % (threading.activeCount() - 2))
def main(): start = u'!' pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'weblinkchecker') if arg: if arg.startswith('-start:'): start = arg[7:] else: pageTitle.append(arg) if pageTitle == []: gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle = ' '.join(pageTitle) page = wikiped...
while bot.history.reportThread.isAlive(): time.sleep(0.1)
try: while bot.history.reportThread.isAlive(): time.sleep(0.1) except KeyboardInterrupt: pass
def main(): start = u'!' pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'weblinkchecker') if arg: if arg.startswith('-start:'): start = arg[7:] else: pageTitle.append(arg) if pageTitle == []: gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle = ' '.join(pageTitle) page = wikiped...
def __init__(self, url):
def __init__(self, url, redirectList = []): """ redirectList is a list of redirects which were resolved by resolveRedirect(). This is needed to detect redirect loops. """
def __init__(self, url): self.url = url # we ignore the fragment self.scheme, self.host, self.path, self.query, self.fragment = urlparse.urlsplit(self.url) if not self.path: self.path = '/' if self.query: self.query = '?' + self.query #header = {'User-agent': 'PythonWikipediaBot/1.0'} # we fake being Opera because some...
redirChecker = LinkChecker(url) return redirChecker.check()
if url in self.redirectList: self.redirectList.append(url) return False, u'HTTP Redirect Loop: %s' % ' -> '.join(self.redirectList) else: self.redirectList.append(url) redirChecker = LinkChecker(url, self.redirectList) return redirChecker.check()
def check(self): try: url = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' if url: redirChecker = LinkChecker(url) return redirChecker.c...
catContentDB[cat] = [subcatlist, articlelist]
catContentDB[supercat] = [subcatlist, articlelist]
def get_subcats(supercat): ''' For a given supercategory, return a list of CatLinks for all its subcategories. Saves this list in a temporary database so that it won't be loaded from the server next time it's required. ''' # if we already know which subcategories exist here if catContentDB.has_key(supercat): return cat...
s = interwikiFormat(new, incode = mylang)
s = interwikiFormat(new)
def replaceLanguageLinks(oldtext, new): """Replace the interwiki language links given in the wikitext given in oldtext by the new links given in new. 'new' should be a dictionary with the language names as keys, and either PageLink objects or the link-names of the pages as values. """ s = interwikiFormat(new, incode =...
def interwikiFormat(links, incode):
def interwikiFormat(links):
def interwikiFormat(links, incode): """Create a suitable string encoding all interwiki links for a wikipedia page. 'links' should be a dictionary with the language names as keys, and either PageLink objects or the link-names of the pages as values. 'incode' should be the name of the wikipedia language that is the tar...
'incode' should be the name of the wikipedia language that is the target of the string.
The string is formatted for inclusion in mylang.
def interwikiFormat(links, incode): """Create a suitable string encoding all interwiki links for a wikipedia page. 'links' should be a dictionary with the language names as keys, and either PageLink objects or the link-names of the pages as values. 'incode' should be the name of the wikipedia language that is the tar...
return unicodeName(s, language = incode)
return s
def interwikiFormat(links, incode): """Create a suitable string encoding all interwiki links for a wikipedia page. 'links' should be a dictionary with the language names as keys, and either PageLink objects or the link-names of the pages as values. 'incode' should be the name of the wikipedia language that is the tar...
if code2encoding(incode) == code2encoding(code):
if code2encoding(incode) == 'utf-8': return x elif code2encoding(incode) == code2encoding(code):
def url2link(percentname,incode,code): """Convert a url-name of a page into a proper name for an interwiki link the argument 'incode' specifies the encoding of the target wikipedia """ result = underline2space(percentname) x = url2unicode(result, language = code) if code2encoding(incode) == code2encoding(code): #print ...