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 = WikimediaXmlHandler() handler.setCallback(self.oneDone) try: xml.sax.parseString(data, handler) except xml.sax._exceptions.SAXParseException: f=open('sax_parse_bug.dat','w') f.write(data) f.close() print "Dumped invalid XML to sax_parse_bug.dat" raise # All of the ones that have not been found apparently do not exist for pl in self.pages: if not hasattr(pl,'_contents') and not hasattr(pl,'_getexception'): if self.site.lang == 'eo': if pl.hashfreeLinkname() != pl.hashfreeLinkname(doublex = True): # Maybe we have used x-convention when we should not? try: pl.get(force = True) except NoPage: pass except IsRedirectPage,arg: pass except LockedPage: pass except SectionError: pass else: pl._getexception = NoPage else: pl._getexception = NoPage if hasattr(pl,'_contents') and pl.site().lang=="eo": # Edit-pages on eo: use X-convention, XML export does not. # Double X-es where necessary so that we can submit a changed # page later. for c in 'C','G','H','J','S','U': for c2 in c,c.lower(): for x in 'X','x': pl._contents = pl._contents.replace(c2+x,c2+x+x)
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 = WikimediaXmlHandler() handler.setCallback(self.oneDone) try: xml.sax.parseString(data, handler) except xml.sax._exceptions.SAXParseException: f=open('sax_parse_bug.dat','w') f.write(data) f.close() print "Dumped invalid XML to sax_parse_bug.dat" raise # All of the ones that have not been found apparently do not exist for pl in self.pages: if not hasattr(pl,'_contents') and not hasattr(pl,'_getexception'): if self.site.lang == 'eo': if pl.hashfreeLinkname() != pl.hashfreeLinkname(doublex = True): # Maybe we have used x-convention when we should not? try: pl.get(force = True) except NoPage: pass except IsRedirectPage,arg: pass except LockedPage: pass except SectionError: pass else: pl._getexception = NoPage else: pl._getexception = NoPage if hasattr(pl,'_contents') and pl.site().lang=="eo": # Edit-pages on eo: use X-convention, XML export does not. # Double X-es where necessary so that we can submit a changed # page later. for c in 'C','G','H','J','S','U': for c2 in c,c.lower(): for x in 'X','x': pl._contents = pl._contents.replace(c2+x,c2+x+x)
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 not self.site().gettoken(): output(u"Getting page to get a token.") self.get(force = True) return putPage(self.site(), self.urlname(), newtext, comment, watchArticle, minorEdit, newPage, self.site().token)
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 - the page name get_edit_page - If true, gets the edit page, otherwise gets the normal page. read_only - If true, doesn't raise LockedPage exceptions. do_quote - ??? (TODO: what is this for?) get_redirect - Get the contents, even if it is a redirect page This routine returns a unicode string containing the wiki text if get_edit_page is True; otherwise it returns a unicode string containing the entire page's HTML code. """ host = site.hostname() name = re.sub(' ', '_', name) output(url2unicode(u'Getting page %s' % site.linkto(name), site = site)) # A heuristic to encode the URL into %XX for characters that are not # allowed in a URL. if not '%' in name and do_quote: # It should not have been done yet if name != urllib.quote(name): print "DBG> quoting",name name = urllib.quote(name) address = site.get_address(name) if get_edit_page: address += '&action=edit&printable=yes' # Make sure Brion doesn't get angry by waiting if the last time a page # was retrieved was not long enough ago. if throttle: get_throttle() # Try to retrieve the page until it was successfully loaded (just in case # the server is down or overloaded) # wait for retry_idle_time minutes (growing!) between retries. retry_idle_time = 1 while True: starttime = time.time() text, charset = getUrl(host, address, site) get_throttle.setDelay(time.time() - starttime)\ # Extract the actual text from the textedit field if get_edit_page: if charset is None: print "WARNING: No character set found" else: # Store character set for later reference site.checkCharset(charset) if not read_only: # check if we're logged in p=re.compile('userlogin') if p.search(text) != None: output(u'Warning: You\'re probably not logged in on %s:' % repr(site)) m = re.search('value="(\d+)" name=\'wpEdittime\'',text) if m: edittime[repr(site), link2url(name, site = site)] = m.group(1) else: m = re.search('value="(\d+)" name="wpEdittime"',text) if m: edittime[repr(site), link2url(name, site = site)] = m.group(1) else: edittime[repr(site), link2url(name, site = site)] = "0" try: i1 = re.search('<textarea[^>]*>', text).end() except AttributeError: # We assume that the server is down. Wait some time, then try again. print "WARNING: No text area found on %s%s. Maybe the server is down. Retrying in %d minutes..." % (host, address, retry_idle_time) time.sleep(retry_idle_time * 60) # Next time wait longer, but not longer than half an hour retry_idle_time *= 2 if retry_idle_time > 30: retry_idle_time = 30 continue i2 = re.search('</textarea>', text).start() if i2-i1 < 2: raise NoPage(site, name) m = redirectRe(site).match(text[i1:i2]) if m and not get_redirect: output(u"DBG> %s is redirect to %s" % (url2unicode(name, site = site), unicode(m.group(1), site.encoding()))) raise IsRedirectPage(m.group(1)) if edittime[repr(site), link2url(name, site = site)] == "0" and not read_only: print "DBG> page may be locked?!" raise LockedPage() x = text[i1:i2] x = unescape(x) while x and x[-1] in '\n ': x = x[:-1] else: x = text # If not editing # Convert to a unicode string. If there's invalid unicode data inside # the page, replace it with question marks. x = unicode(x, charset, errors = 'replace') # Looking for the token 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('') return x
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 - the page name get_edit_page - If true, gets the edit page, otherwise gets the normal page. read_only - If true, doesn't raise LockedPage exceptions. do_quote - ??? (TODO: what is this for?) get_redirect - Get the contents, even if it is a redirect page This routine returns a unicode string containing the wiki text if get_edit_page is True; otherwise it returns a unicode string containing the entire page's HTML code. """ host = site.hostname() name = re.sub(' ', '_', name) output(url2unicode(u'Getting page %s' % site.linkto(name), site = site)) # A heuristic to encode the URL into %XX for characters that are not # allowed in a URL. if not '%' in name and do_quote: # It should not have been done yet if name != urllib.quote(name): print "DBG> quoting",name name = urllib.quote(name) address = site.get_address(name) if get_edit_page: address += '&action=edit&printable=yes' # Make sure Brion doesn't get angry by waiting if the last time a page # was retrieved was not long enough ago. if throttle: get_throttle() # Try to retrieve the page until it was successfully loaded (just in case # the server is down or overloaded) # wait for retry_idle_time minutes (growing!) between retries. retry_idle_time = 1 while True: starttime = time.time() text, charset = getUrl(host, address, site) get_throttle.setDelay(time.time() - starttime)\ # Extract the actual text from the textedit field if get_edit_page: if charset is None: print "WARNING: No character set found" else: # Store character set for later reference site.checkCharset(charset) if not read_only: # check if we're logged in p=re.compile('userlogin') if p.search(text) != None: output(u'Warning: You\'re probably not logged in on %s:' % repr(site)) m = re.search('value="(\d+)" name=\'wpEdittime\'',text) if m: edittime[repr(site), link2url(name, site = site)] = m.group(1) else: m = re.search('value="(\d+)" name="wpEdittime"',text) if m: edittime[repr(site), link2url(name, site = site)] = m.group(1) else: edittime[repr(site), link2url(name, site = site)] = "0" try: i1 = re.search('<textarea[^>]*>', text).end() except AttributeError: # We assume that the server is down. Wait some time, then try again. print "WARNING: No text area found on %s%s. Maybe the server is down. Retrying in %d minutes..." % (host, address, retry_idle_time) time.sleep(retry_idle_time * 60) # Next time wait longer, but not longer than half an hour retry_idle_time *= 2 if retry_idle_time > 30: retry_idle_time = 30 continue i2 = re.search('</textarea>', text).start() if i2-i1 < 2: raise NoPage(site, name) m = redirectRe(site).match(text[i1:i2]) if m and not get_redirect: output(u"DBG> %s is redirect to %s" % (url2unicode(name, site = site), unicode(m.group(1), site.encoding()))) raise IsRedirectPage(m.group(1)) if edittime[repr(site), link2url(name, site = site)] == "0" and not read_only: print "DBG> page may be locked?!" raise LockedPage() x = text[i1:i2] x = unescape(x) while x and x[-1] in '\n ': x = x[:-1] else: x = text # If not editing # Convert to a unicode string. If there's invalid unicode data inside # the page, replace it with question marks. x = unicode(x, charset, errors = 'replace') # Looking for the token 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('') return x
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 where this link was found. """ self._site = site if tosite: self._tosite = tosite else: self._tosite = getSite() # Default to home wiki # Clean up the name, it can come from anywhere. # Replace underlines by spaces title = underline2space(title) # Convert HTML entities to unicode title = html2unicode(title, site = site, altsite = insite) # Convert URL-encoded characters to unicode title = url2unicode(title, site = site) # replace cx by ĉ etc. if site.lang == 'eo': title = resolveEsperantoXConvention(title) # Remove double spaces while ' ' in title: title = title.replace(' ', ' ') # Remove leading colon if title.startswith(':'): title = title[1:] # split up into namespace and rest title = title.split(':', 1) # if the page is not in namespace 0: if len(title) > 1: # translate a default namespace name into the local namespace name for ns in site.family.namespaces.keys(): if title[0] == site.family.namespace('_default', ns): title[0] = site.namespace(ns) # Capitalize the first non-namespace part for ns in site.family.namespaces.keys(): if title[0] == site.namespace(ns): # Remove leading and trailing whitespace from namespace and from rest for i in range(len(title)): title[i] = title[i].strip() if not site.nocapitalize: try: title[1] = title[1][0].upper()+title[1][1:] except IndexError: # title[1] is empty print "WARNING: Strange title %s"%'%3A'.join(title) # In case the part before the colon was not a namespace, we need to # remove leading and trailing whitespace now. title = ':'.join(title).strip() # Capitalize first letter try: if not site.nocapitalize: title = title[0].upper() + title[1:] except IndexError: # title is empty pass self._title = title
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].capitalize() + x[1:]) name = '_'.join(n) #print name else: name = re.sub(' ', '_', name) if not '%' in name and do_quote: # It should not have been done yet if name != urllib.quote(name): print "DBG> quoting",name name = urllib.quote(name) if code not in oldsoftware: address = '/w/wiki.phtml?title='+name+"&redirect=no" if do_edit: address += '&action=edit' else: if not do_edit: raise "can not skip edit on old-software wikipedia" address = '/wiki.cgi?action=edit&id='+name if debug: print host, address # Make sure Brion doesn't get angry by slowing ourselves down. throttle() text, charset = getUrl(host,address) # Keep login status for external use global loggedin if "Userlogin" in text: loggedin = False else: loggedin = True # Extract the actual text from the textedit field if do_edit: if debug: print "Raw:", len(text), type(text), text.count('x') if charset is None: print "WARNING: No character set found" else: # Store character set for later reference if charsets.has_key(code): assert charsets[code].lower() == charset.lower(), "charset for %s changed from %s to %s"%(code,charsets[code],charset) charsets[code] = charset if code2encoding(code).lower() != charset.lower(): raise ValueError("code2encodings has wrong charset for %s. It should be %s"%(code,charset)) if debug>1: print repr(text) m = re.search('value="(\d+)" name=\'wpEdittime\'',text) if m: edittime[code, link2url(name, code)] = m.group(1) else: m = re.search('value="(\d+)" name="wpEdittime"',text) if m: edittime[code, link2url(name, code)] = m.group(1) else: edittime[code, link2url(name, code)] = 0 try: i1 = re.search('<textarea[^>]*>', text).end() except AttributeError: #print "No text area.",host,address #print repr(text) raise LockedPage(text) i2 = re.search('</textarea>', text).start() if i2-i1 < 2: # new software raise NoPage() if debug: print text[i1:i2] if text[i1:i2] == 'Describe the new page here.\n': # old software raise NoPage() Rredirect = re.compile(r'\#redirect:? *\[\[(.*?)\]\]', re.I) m=Rredirect.match(text[i1:i2]) if m: raise IsRedirectPage(m.group(1)) if needput: assert edittime[code, name] != 0 or code in oldsoftware, "No edittime on non-empty page?! %s:%s\n%s"%(code,name,text) x = text[i1:i2] x = unescape(x) else: x = text # If not editing if charset == 'utf-8': # Make it to a unicode string encode_func, decode_func, stream_reader, stream_writer = codecs.lookup('utf-8') try: x,l = decode_func(x) except UnicodeError: print code,name print repr(x) raise # Convert the unicode characters to &# references, and make it ascii. x = str(UnicodeToAsciiHtml(x)) return x
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 hints.has_key(m.group(2)): hints[m.group(2)]=[] #print m.group(3) if m.group(3) != ' links to incorrect ': try: hints[m.group(2)].append('%s:%s'%(m.group(4),wikipedia.link2url(m.group(5),m.group(4)))) except wikipedia.Error: print "DBG> Failed to add", line #print "DBG> %s : %s" % (m.group(2), hints[m.group(2)]) f.close() for pagename in hints: pl = wikipedia.PageLink(wikipedia.mylang, pagename) sa.add(pl, hints = hints[pagename])
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.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 webservers block # unknown clients self.header = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050511 Firefox/1.0.4 SUSE/1.0.4-0.3'}
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.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 webservers block # unknown clients self.header = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050511 Firefox/1.0.4 SUSE/1.0.4-0.3'}
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 UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' if url: 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() else: # TODO: HTTPS try: conn = httplib.HTTPConnection(self.host) except httplib.error, arg: return False, u'HTTP Error: %s' % arg try: conn.request('GET', '%s%s' % (self.path, self.query), None, self.header) except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' try: response = conn.getresponse() except Exception, arg: return False, u'Error: %s' % arg #wikipedia.output('%s: %s' % (self.url, response.status)) # site down if the server status is between 400 and 499 siteDown = response.status in range(400, 500) return not siteDown, '%s %s' % (response.status, response.reason)
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 UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' if url: 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() else: # TODO: HTTPS try: conn = httplib.HTTPConnection(self.host) except httplib.error, arg: return False, u'HTTP Error: %s' % arg try: conn.request('GET', '%s%s' % (self.path, self.query), None, self.header) except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' try: response = conn.getresponse() except Exception, arg: return False, u'Error: %s' % arg #wikipedia.output('%s: %s' % (self.url, response.status)) # site down if the server status is between 400 and 499 siteDown = response.status in range(400, 500) return not siteDown, '%s %s' % (response.status, response.reason)
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 UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' if url: 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() else: # TODO: HTTPS try: conn = httplib.HTTPConnection(self.host) except httplib.error, arg: return False, u'HTTP Error: %s' % arg try: conn.request('GET', '%s%s' % (self.path, self.query), None, self.header) except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' try: response = conn.getresponse() except Exception, arg: return False, u'Error: %s' % arg #wikipedia.output('%s: %s' % (self.url, response.status)) # site down if the server status is between 400 and 499 siteDown = response.status in range(400, 500) return not siteDown, '%s %s' % (response.status, response.reason)
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 # right parenthesis at the end of the URL as not part of that URL. # So characters inside the URL can be anything except whitespace and # closing squared brackets, and the last character also can't be right # parenthesis. linkR = re.compile(r'http://[^\]\s]*[^\]\)\s]') urls = linkR.findall(text) for url in urls: # Limit the number of threads started at the same time. Each # thread will check one page, then die. while threading.activeCount() >= config.max_external_links: # wait 100 ms time.sleep(0.1) thread = LinkCheckThread(title, url, self.history) # thread dies when program terminates thread.setDaemon(True) thread.start()
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:] source = 'sqldump' elif arg.startswith('-start:'): start = arg[7:] else: pageTitle.append(arg) source = 'page' if source == 'sqldump': # Bot will read all wiki pages from the dump and won't access the wiki. wikipedia.stopme() gen = SqlPageGenerator(sqlfilename) elif source == 'page': pageTitle = ' '.join(pageTitle) pl = wikipedia.Page(wikipedia.getSite(), pageTitle) gen = SinglePageGenerator(pl) else: gen = AllpagesPageGenerator(start) bot = WeblinkCheckerRobot(gen) try: bot.run() finally: i = 0 # Don't wait longer than 10 seconds for threads to finish. while threading.activeCount() > 1 and i < 10: wikipedia.output(u"Waiting for remaining %i threads to finish, please wait..." % (threading.activeCount() - 1)) # don't count the main thread # wait 1 second time.sleep(1) i += 1 if threading.activeCount() > 1: wikipedia.output(u"Killing remaining %i threads..." % threading.activeCount()) # Threads will die automatically because they are daemonic bot.history.save()
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.translate(wikipedia.getSite(), comment) titleroot.move(pagemove, msg) wikipedia.output('Page %s move successful to %s.' % (pagetitle, pagemove)) pagedel = wikipedia.Page(wikipedia.getSite(), pagetitle) pagedel.delete(pagetitle) elif ask == 'n': pass elif ask == 'q': sys.exit() else: wikipedia.output('Input certain code.') sys.exit()
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.translate(wikipedia.getSite(), comment) titleroot.move(pagemove, msg) wikipedia.output('Page %s move successful to %s.' % (pagetitle, pagemove)) pagedel = wikipedia.Page(wikipedia.getSite(), pagetitle) pagedel.delete(pagetitle) elif ask == 'n': pass elif ask == 'q': sys.exit() else: wikipedia.output('Input certain code.') sys.exit()
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'): if len(arg) == 4: referredPageTitle = wikipedia.input(u'Links to which page should be processed?') else: referredPageTitle = arg[5:] else: singlePageTitle.append(arg) if categoryName: cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % categoryName) gen = pagegenerators.CategorizedPageGenerator(cat) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for page in generator: Movepages(page) elif referredPageTitle: referredPage = wikipedia.Page(wikipedia.getSite(), referredPageTitle) gen = pagegenerators.ReferringPageGenerator(referredPage) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for page in generator: Movepages(page) else: singlePageTitle = ' '.join(singlePageTitle) if not singlePageTitle: singlePageTitle = wikipedia.input(u'Which page to move:') singlePage = wikipedia.Page(wikipedia.getSite(), singlePageTitle) Movepages(singlePage)
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 page in generator: MovepageswithPrefix(page, prefixPageTitle, 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'): if len(arg) == 4: referredPageTitle = wikipedia.input(u'Links to which page should be processed?') else: referredPageTitle = arg[5:] else: singlePageTitle.append(arg) if categoryName: cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % categoryName) gen = pagegenerators.CategorizedPageGenerator(cat) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for page in generator: Movepages(page) elif referredPageTitle: referredPage = wikipedia.Page(wikipedia.getSite(), referredPageTitle) gen = pagegenerators.ReferringPageGenerator(referredPage) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for page in generator: Movepages(page) else: singlePageTitle = ' '.join(singlePageTitle) if not singlePageTitle: singlePageTitle = wikipedia.input(u'Which page to move:') singlePage = wikipedia.Page(wikipedia.getSite(), singlePageTitle) Movepages(singlePage)
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'): if len(arg) == 4: referredPageTitle = wikipedia.input(u'Links to which page should be processed?') else: referredPageTitle = arg[5:] else: singlePageTitle.append(arg) if categoryName: cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % categoryName) gen = pagegenerators.CategorizedPageGenerator(cat) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for page in generator: Movepages(page) elif referredPageTitle: referredPage = wikipedia.Page(wikipedia.getSite(), referredPageTitle) gen = pagegenerators.ReferringPageGenerator(referredPage) generator = pagegenerators.PreloadingGenerator(gen, pageNumber = []) for page in generator: Movepages(page) else: singlePageTitle = ' '.join(singlePageTitle) if not singlePageTitle: singlePageTitle = wikipedia.input(u'Which page to move:') singlePage = wikipedia.Page(wikipedia.getSite(), singlePageTitle) Movepages(singlePage)
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" print "answer to the first question." listpage = wikipedia.input('Wikipedia page with list of pages to change: ') if listpage: try: pl = wikipedia.PageLink(wikipedia.mylang, listpage) except NoPage: print 'The page ' + listpage + ' could not be loaded from the server.' sys.exit() pagenames = pl.links() else: refpage = wikipedia.input('Wikipedia page that is now linked to: ') pl = wikipedia.PageLink(wikipedia.mylang, refpage) pagenames = wikipedia.getReferences(pl) print " ==> %d pages to process"%len(pagenames) print newcat = wikipedia.input('Category to add (do not give namespace) : ') newcat = newcat.encode(wikipedia.code2encoding(wikipedia.mylang)) newcat = newcat[:1].capitalize() + newcat[1:] ns = wikipedia.family.category_namespaces(wikipedia.mylang) cat_namespace = ns[0].encode(wikipedia.code2encoding(wikipedia.mylang)) if not sort_by_last_name: catpl = wikipedia.PageLink(wikipedia.mylang, cat_namespace + ':' + newcat) print "Will add %s"%catpl.aslocallink() answer = '' for nm in pagenames: pl2 = wikipedia.PageLink(wikipedia.mylang, nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input("%s [y/n/a(ll)] : "%(pl2.asasciilink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input("This should be used if and only if you are sure that your links are correct !!! Are you sure ? [y/n] : ") if answer == 'y' or answer == 'a': try: cats = pl2.categories() except wikipedia.NoPage: print "%s doesn't exist yet. Ignoring."%(pl2.aslocallink()) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.PageLink(wikipedia.mylang,arg.args[0]) print "WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink()) else: print "Current categories: ",cats if sort_by_last_name: page_name = pl2.linkname() split_string = page_name.split(' ') if len(split_string) > 1: # pull last part of the name to the beginning, and append the rest after a comma # e.g. "John von Neumann" becomes "Neumann, John von" new_name = split_string[-1] + ', ' + string.join(split_string[:-1], ' ') # give explicit sort key catpl = wikipedia.PageLink(wikipedia.mylang, cat_namespace + ':' + newcat + '|' + new_name) else: catpl = wikipedia.PageLink(wikipedia.mylang, cat_namespace + ':' + newcat) if catpl in cats: print "%s already has %s"%(pl2.aslocallink(),catpl.aslocallink()) else: cats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, cats) pl2.put(text, comment = catpl.aslocallink().encode(wikipedia.code2encoding(wikipedia.mylang)))
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"Updating links on page %s." % pl.aslink(forceInterwiki = True))
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 for pl in self.pending: # Mark the page as done self.done[pl] = pl.site() # Register this fact at the todo-counter. counter.minus(pl.site()) # Assume it's not a redirect isredirect = 0 # Now check whether any interwiki links should be added to the # todo list. if pl.section(): # We have been referred to a part of a page, not the whole page. Do not follow references. pass else: try: iw = pl.interwiki() except wikipedia.IsRedirectPage,arg: 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: # This is a redirect page itself. We don't need to # follow the redirection. isredirect = 1 # In this case we can also stop all hints! for pl2 in self.todo: counter.minus(pl2.site()) self.todo = {} pass elif not globalvar.followredirect: print "NOTE: not following redirects." else: if self.conditionalAdd(pl3, counter, pl): if globalvar.shownew: wikipedia.output(u"%s: %s gives new redirect %s" % (self.inpl.aslink(), pl.aslink(forceInterwiki = True), pl3.aslink(forceInterwiki = True))) except wikipedia.NoPage: wikipedia.output(u"NOTE: %s does not exist" % pl.aslink(forceInterwiki = True)) #print "DBG> ",pl.urlname() if pl == self.inpl: # This is the home subject page. # In this case we can stop all hints! for pl2 in self.todo: counter.minus(pl2.site()) self.todo = {} self.done = {} # In some rare cases it might be we already did check some 'automatic' links pass #except wikipedia.SectionError: # wikipedia.output(u"NOTE: section %s does not exist" % pl.aslink()) else: if not globalvar.autonomous: if self.inpl.isDisambig() and not pl.isDisambig(): choice = wikipedia.inputChoice('WARNING: %s is a disambiguation page, but %s doesn\'t seem to be one. Follow it anyway?' % (self.inpl.aslink(forceInterwiki = True), pl.aslink(forceInterwiki = True)), ['Yes', 'No', 'Add a hint'], ['y', 'N', 'A'], 'N') elif not self.inpl.isDisambig() and pl.isDisambig(): choice = wikipedia.inputChoice('WARNING: %s doesn\'t seem to be a disambiguation page, but %s is one. Follow it anyway?' % (self.inpl.aslink(forceInterwiki = True), pl.aslink(forceInterwiki = True)), ['Yes', 'No', 'Add a hint'], ['y', 'N', 'A'], 'N') else: choice = 'y' if choice not in ['y', 'Y']: wikipedia.output(u"NOTE: ignoring %s and its interwiki links" % pl.aslink(forceInterwiki = True)) del self.done[pl] iw = () if choice in ['a', 'A']: newhint = wikipedia.input(u'Give a hint for language %s, not using a language code:'%pl.site().language()) if newhint: page2 = wikipedia.Page(pl.site(),newhint) self.conditionalAdd(page2, counter, None) if self.inpl == pl: self.untranslated = (len(iw) == 0) if globalvar.untranslatedonly: # Ignore the interwiki links. iw = () elif pl.isEmpty(): if not pl.isCategory(): wikipedia.output(u"NOTE: %s is empty; ignoring it and its interwiki links" % pl.aslink(forceInterwiki = True)) # Ignore the interwiki links iw = () for page2 in iw: if page2.site().language() in globalvar.neverlink: print "Skipping link %s to an ignored language"% page2 continue if globalvar.same=='wiktionary' and page2.title().lower()!=self.inpl.title().lower(): print "NOTE: Ignoring %s for %s in wiktionary mode"% (page2, self.inpl) continue if not globalvar.autonomous: if self.inpl.namespace() != page2.namespace(): if not self.foundin.has_key(page2): choice = wikipedia.inputChoice('WARNING: %s is in namespace %i, but %s is in namespace %i. Follow it anyway?' % (self.inpl.aslink(forceInterwiki = True), self.inpl.namespace(), page2.aslink(forceInterwiki = True), page2.namespace()), ['Yes', 'No'], ['y', 'N'], 'N') if choice not in ['y', 'Y']: # Fill up foundin, so that we will not ask again self.foundin[page2] = pl wikipedia.output(u"NOTE: ignoring %s and its interwiki links" % pl.aslink(forceInterwiki = True)) continue if self.conditionalAdd(page2, counter, pl): if globalvar.shownew: wikipedia.output(u"%s: %s gives new interwiki %s"% (self.inpl.aslink(), pl.aslink(forceInterwiki = True), page2.aslink(forceInterwiki = True))) # These pages are no longer 'in progress' del self.pending # Check whether we need hints and the user offered to give them if self.untranslated and not self.hintsasked: wikipedia.output(u"NOTE: %s does not have any interwiki links" % self.inpl.aslink(forceInterwiki = True)) if (self.untranslated or globalvar.askhints) and not self.hintsasked and not isredirect: # Only once! self.hintsasked = True if globalvar.untranslated: newhint = None t = globalvar.showtextlink if t: wikipedia.output(pl.get()[:t]) while 1: newhint = wikipedia.input(u'Give a hint (? to see pagetext):') if newhint == '?': t += globalvar.showtextlinkadd wikipedia.output(pl.get()[:t]) elif newhint and not ':' in newhint: print "Please enter a hint like language:pagename" print "or type nothing if you do not have a hint" elif not newhint: break else: arr = {} titletranslate.translate(pl, arr, same = False, hints = [newhint], auto = globalvar.auto) for pl2 in arr.iterkeys(): self.todo[pl2] = pl2.site() counter.plus(pl2.site()) self.foundin[pl2] = [None]
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 pl in self.pending: # Mark the page as done self.done[pl] = pl.code() # Register this fact at the todo-counter. counter.minus(pl.code())
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 may need to retrieve a second home-language page! if len(self.subjects) - mycount < globalvar.minarraysize: # Can we make more home-language queries by adding subjects? if self.generator and mycount < globalvar.maxquerysize: self.generateMore(globalvar.maxquerysize - mycount) # If we have a few, getting the home language is a good thing. if self.counts[wikipedia.mylang] > 4: return wikipedia.mylang # If getting the home language doesn't make sense, see how many # foreign page queries we can find. maxlang, max = self.maxOpenCode() return maxlang
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 = [] for s in _reParameters.split(pattern): if s is None: pass elif len(s) in [2,3] and s[0]=='%' and s[-1] in _digitDecoders and (len(s)==2 or s[1] in _decimalDigits): # Must match a "%2d" or "%d" style dec = _digitDecoders[s[-1]] if type(dec) in _stringTypes: # Special case for strings that are replaced instead of decoded if len(s) == 3: raise AssertionError("Invalid pattern %s: Cannot use zero padding size in %s!" % (pattern, s)) newPattern += re.escape( dec ) strPattern += s # Keep the original text else: if len(s) == 3: raise AssertionError("Invalid pattern %s: Zero padding size is not yet implemented!" % pattern) newPattern += u'([%s]{%s})' % (dec[0], s[1]) # enforce mandatory field size else: newPattern += u'([%s]+)' % dec[0] decoders.append( dec ) strPattern += u'%s' # All encoders produce a string # this causes problem with the zero padding. Need to rethink else: newPattern += re.escape( s ) strPattern += s newPattern += u'$' # end of the string compiledPattern = re.compile( newPattern ) _escPtrnCache2[pattern] = (compiledPattern, strPattern, decoders) return _escPtrnCache2[pattern]
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 pattern, each integer will be converted to a proper string representation, and will be passed as a format argument to the pattern: pattern % encodingFunc(value) This function is a complement of decodingFunc. decodingFunc: Converts a tuple/list of non-negative integers found in the original value string into a normalized value. The normalized value can be passed right back into dh() to produce the original string. This function is a complement of encodingFunc. dh() interprets %d as a decimal and %s as a roman numeral number. """ compPattern, strPattern, decoders = escapePattern2(pattern) if type(value) in _stringTypes: m = compPattern.match(value) if m: # decode each found value using provided decoder values = [ decoders[i][2](m.group(i+1)) for i in range(len(decoders))] decValue = decf( values ) if decValue in _stringTypes: raise AssertionError("Decoder must not return a string!") # recursive call to re-encode and see if we get the original (may through filter exception) if value == dh(decValue, pattern, encf, decf, filter): return decValue raise ValueError("reverse encoding didn't match") else: # Encode an integer value into a textual form. # This will be called from outside as well as recursivelly to verify parsed value if filter and not filter(value): raise ValueError("value %i is not allowed" % value) params = encf(value) if type(params) in _listTypes: if len(params) != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameters into their textual representation params = [ decoders[i][1](params[i]) for i in range(len(params)) ] return strPattern % tuple(params) else: if 1 != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameter into its textual representation params = decoders[0][1](params) return strPattern % params
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 pattern, each integer will be converted to a proper string representation, and will be passed as a format argument to the pattern: pattern % encodingFunc(value) This function is a complement of decodingFunc. decodingFunc: Converts a tuple/list of non-negative integers found in the original value string into a normalized value. The normalized value can be passed right back into dh() to produce the original string. This function is a complement of encodingFunc. dh() interprets %d as a decimal and %s as a roman numeral number. """ compPattern, strPattern, decoders = escapePattern2(pattern) if type(value) in _stringTypes: m = compPattern.match(value) if m: # decode each found value using provided decoder values = [ decoders[i][2](m.group(i+1)) for i in range(len(decoders))] decValue = decf( values ) if decValue in _stringTypes: raise AssertionError("Decoder must not return a string!") # recursive call to re-encode and see if we get the original (may through filter exception) if value == dh(decValue, pattern, encf, decf, filter): return decValue raise ValueError("reverse encoding didn't match") else: # Encode an integer value into a textual form. # This will be called from outside as well as recursivelly to verify parsed value if filter and not filter(value): raise ValueError("value %i is not allowed" % value) params = encf(value) if type(params) in _listTypes: if len(params) != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameters into their textual representation params = [ decoders[i][1](params[i]) for i in range(len(params)) ] return strPattern % tuple(params) else: if 1 != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameter into its textual representation params = decoders[0][1](params) return strPattern % params
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 pattern, each integer will be converted to a proper string representation, and will be passed as a format argument to the pattern: pattern % encodingFunc(value) This function is a complement of decodingFunc. decodingFunc: Converts a tuple/list of non-negative integers found in the original value string into a normalized value. The normalized value can be passed right back into dh() to produce the original string. This function is a complement of encodingFunc. dh() interprets %d as a decimal and %s as a roman numeral number. """ compPattern, strPattern, decoders = escapePattern2(pattern) if type(value) in _stringTypes: m = compPattern.match(value) if m: # decode each found value using provided decoder values = [ decoders[i][2](m.group(i+1)) for i in range(len(decoders))] decValue = decf( values ) if decValue in _stringTypes: raise AssertionError("Decoder must not return a string!") # recursive call to re-encode and see if we get the original (may through filter exception) if value == dh(decValue, pattern, encf, decf, filter): return decValue raise ValueError("reverse encoding didn't match") else: # Encode an integer value into a textual form. # This will be called from outside as well as recursivelly to verify parsed value if filter and not filter(value): raise ValueError("value %i is not allowed" % value) params = encf(value) if type(params) in _listTypes: if len(params) != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameters into their textual representation params = [ decoders[i][1](params[i]) for i in range(len(params)) ] return strPattern % tuple(params) else: if 1 != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameter into its textual representation params = decoders[0][1](params) return strPattern % params
'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 pattern, each integer will be converted to a proper string representation, and will be passed as a format argument to the pattern: pattern % encodingFunc(value) This function is a complement of decodingFunc. decodingFunc: Converts a tuple/list of non-negative integers found in the original value string into a normalized value. The normalized value can be passed right back into dh() to produce the original string. This function is a complement of encodingFunc. dh() interprets %d as a decimal and %s as a roman numeral number. """ compPattern, strPattern, decoders = escapePattern2(pattern) if type(value) in _stringTypes: m = compPattern.match(value) if m: # decode each found value using provided decoder values = [ decoders[i][2](m.group(i+1)) for i in range(len(decoders))] decValue = decf( values ) if decValue in _stringTypes: raise AssertionError("Decoder must not return a string!") # recursive call to re-encode and see if we get the original (may through filter exception) if value == dh(decValue, pattern, encf, decf, filter): return decValue raise ValueError("reverse encoding didn't match") else: # Encode an integer value into a textual form. # This will be called from outside as well as recursivelly to verify parsed value if filter and not filter(value): raise ValueError("value %i is not allowed" % value) params = encf(value) if type(params) in _listTypes: if len(params) != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameters into their textual representation params = [ decoders[i][1](params[i]) for i in range(len(params)) ] return strPattern % tuple(params) else: if 1 != len(decoders): raise AssertionError("parameter count (%d) does not match decoder count (%d)" % (len(params), len(decoders))) # convert integer parameter into its textual representation params = decoders[0][1](params) return strPattern % params
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. curpos = m.start() + 1 # Try to standardize the page. try: linkpl=wikipedia.PageLink(thispl.code(), m.group(1), incode = refpl.code()) except wikipedia.NoSuchEntity: # Probably this is an interwiki link.... linkpl = None # Check whether the link found is to thispl. if linkpl != thispl: continue n += 1 context = 30 while 1: print "== %s =="%(refpl) print wikipedia.UnicodeToAsciiHtml(reftxt[max(0,m.start()-context):m.end()+context]) choice=raw_input("Option (#,r#,s=skip link,n=next page,u=unlink,q=quit,\n" " m=more context,l=list,a=add new):") if choice=='n': return True elif choice=='s': choice=-1 break elif choice=='u': choice=-2 break elif choice=='a': ns=raw_input('New alternative:') alternatives.append(ns) elif choice=='q': return False elif choice=='m': context*=2 elif choice=='l': for i in range(len(alternatives)): print "%3d" % i,repr(alternatives[i]) else: if choice[0] == 'r': replaceit = 1 choice = choice[1:] else: replaceit = 0 try: choice=int(choice) except ValueError: pass else: break if choice==-1: # Next link on this page continue g1 = m.group(1) g2 = m.group(2) if not g2: g2 = g1 if choice==-2: # unlink reftxt = reftxt[:m.start()] + g2 + reftxt[m.end():] else: # Normal replacement replacement = alternatives[choice] reppl = wikipedia.PageLink(thispl.code(), replacement, incode = refpl.code()) replacement = reppl.linkname() # There is a function that uncapitalizes the link target's first letter # if the link description starts with a small letter. This is useful on # nl: but annoying on de:. # At the moment the de: exclusion is only a workaround because I don't # know if other languages don't want this feature either. # We might want to introduce a list of languages that don't want to use # this feature. if wikipedia.mylang != 'de' and g2[0] in 'abcdefghijklmnopqrstuvwxyz': replacement = replacement[0].lower() + replacement[1:] if replaceit or replacement == g2: reptxt = replacement else: reptxt = "%s|%s" % (replacement, g2) reftxt = reftxt[:m.start()+2] + reptxt + reftxt[m.end()-2:] print wikipedia.UnicodeToAsciiHtml(reftxt[max(0,m.start()-30):m.end()+30]) if not debug: refpl.put(reftxt) return True
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 the user. Arguments: * source - where the bot should retrieve the page list from. can be 'sqldump', 'textfile' or 'userinput'. * replacements - a dictionary where keys are original texts and values are replacement texts. * exceptions - a list of strings; pages which contain one of these won't be changed. * regex - if the entries of replacements and exceptions should be interpreted as regular expressions * namespace - namespace to process in case of a SQL dump * textfilename - the textfile's path, either absolute or relative, which will be used when source is 'textfile'. * sqlfilename - the dump's path, either absolute or relative, which will be used when source is 'sqldump'. * pagenames - a list of pages which will be used when source is 'userinput'. ''' if source == 'sqldump': for pl in read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex, namespace): yield pl elif source == 'textfile': for pl in read_pages_from_text_file(textfilename): yield pl elif source == 'userinput': for pagename in pagenames: yield wikipedia.PageLink(wikipedia.mylang, pagename)
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_message == '': summary_message = default_summary_message wikipedia.setAction(summary_message)
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 the user. Arguments: * source - where the bot should retrieve the page list from. can be 'sqldump', 'textfile' or 'userinput'. * replacements - a dictionary where keys are original texts and values are replacement texts. * exceptions - a list of strings; pages which contain one of these won't be changed. * regex - if the entries of replacements and exceptions should be interpreted as regular expressions * namespace - namespace to process in case of a SQL dump * textfilename - the textfile's path, either absolute or relative, which will be used when source is 'textfile'. * sqlfilename - the dump's path, either absolute or relative, which will be used when source is 'sqldump'. * pagenames - a list of pages which will be used when source is 'userinput'. ''' if source == 'sqldump': for pl in read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex, namespace): yield pl elif source == 'textfile': for pl in read_pages_from_text_file(textfilename): yield pl elif source == 'userinput': for pagename in pagenames: yield wikipedia.PageLink(wikipedia.mylang, pagename)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 "specific page. If you want the second, please give an empty" print "answer to the first question." listpage = wikipedia.input(u'Wikipedia page with list of pages to change:') if listpage: try: pl = wikipedia.Page(wikipedia.getSite(), listpage) except NoPage: wikipedia.output(u'The page ' + listpage + ' could not be loaded from the server.') sys.exit() pagenames = pl.links() else: 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) print newcat = wikipedia.input(u'Category to add (do not give namespace):') newcat = newcat[:1].capitalize() + newcat[1:] # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_add) % newcat) cat_namespace = wikipedia.getSite().category_namespaces()[0] answer = '' for nm in pagenames: pl2 = wikipedia.Page(wikipedia.getSite(), nm) if answer != 'a': answer = '' while answer not in ('y','n','a'): answer = wikipedia.input(u'%s [y/n/a(ll)]:' % (pl2.aslink())) if answer == 'a': confirm = '' while confirm not in ('y','n'): confirm = wikipedia.input(u'This should be used if and only if you are sure that your links are correct! Are you sure? [y/n]:') if answer == 'y' or answer == 'a': try: cats = pl2.categories() rawcats = pl2.rawcategories() except wikipedia.NoPage: wikipedia.output(u"%s doesn't exist yet. Ignoring."%(pl2.aslocallink())) pass except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.Page(wikipedia.getSite(),arg.args[0]) wikipedia.output(u"WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())) else: wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % curpl.aslink()) catpl = wikipedia.Page(wikipedia.getSite(), cat_namespace + ':' + newcat) if sort_by_last_name: catpl = sorted_by_last_name(catpl, pl2) if catpl in cats: wikipedia.output(u"%s already has %s"%(pl2.aslocallink(), catpl.aslocallink())) else: wikipedia.output(u'Adding %s' % catpl.aslocallink()) rawcats.append(catpl) text = pl2.get() text = wikipedia.replaceCategoryLinks(text, rawcats) pl2.put(text)
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 an # interwiki link. # NOTE: This assumes that language codes only consist of non-capital # ASCII letters and hyphens. interwikiR = re.compile(r'\[\[([a-z\-]+):([^\]]*)\]\]') for lang, pagetitle in interwikiR.findall(text): if not pagetitle: print "ERROR: empty link to %s:" % lang # Check if it really is in fact an interwiki link to a known # language, or if it's e.g. a category tag or an internal link elif lang in insite.family.obsolete: lang=insite.family.obsolete[lang] if lang in insite.family.langs: if '|' in pagetitle: # ignore text after the pipe pagetitle = pagetitle[:pagetitle.index('|')] if insite.lang == 'eo': pagetitle=pagetitle.replace('xx','x') if not pagetitle: output(u"ERROR: ignoring impossible link to %s:%s" % (lang, pagetitle)) else: result[insite.getSite(code=lang)] = pagetitle return result
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 list of 2-tuples of original text and replacement text. replacements = [] # Don't edit pages which contain certain texts. exceptions = [] # Should the elements of 'replacements' and 'exceptions' be interpreted # as regular expressions? regex = False # Predefined fixes from dictionary 'fixes' (see above). fix = None # the dump's path, either absolute or relative, which will be used when source # is 'xmldump'. xmlFilename = None useSql = False # the textfile's path, either absolute or relative, which will be used when # source is 'textfile'. textfilename = None # the category name which will be used when source is 'category'. categoryname = None # pages which will be processed when the -page parameter is used PageTitles = [] # a page whose referrers will be processed when the -ref parameter is used referredPageTitle = None # a page whose links will be processed when the -links parameter is used linkingPageTitle = None # will become True when the user presses a ('yes to all') or uses the -always # commandline paramater. acceptall = False # Which namespaces should be processed? # default to [] which means all namespaces will be processed namespaces = [] # Which page to start startpage = None # Google query googleQuery = None # Load default summary message. wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg)) # Read commandline parameters. for arg in wikipedia.handleArgs(): if arg == '-regex': regex = True elif arg.startswith('-file'): if len(arg) >= 6: textfilename = arg[6:] gen = pagegenerators.TextfilePageGenerator(textfilename) elif arg.startswith('-cat'): if len(arg) == 4: categoryname = wikipedia.input(u'Please enter the category name:') else: categoryname = arg[5:] cat = catlib.Category(wikipedia.getSite(), 'Category:%s' % categoryname) gen = pagegenerators.CategorizedPageGenerator(cat) elif arg.startswith('-xml'): if len(arg) == 4: xmlFilename = wikipedia.input(u'Please enter the XML dump\'s filename:') else: xmlFilename = arg[5:] elif arg =='-sql': useSql = True elif arg.startswith('-page'): if len(arg) == 5: PageTitles.append(wikipedia.input(u'Which page do you want to chage?')) else: PageTitles.append(arg[6:]) source = 'specificPages' elif arg.startswith('-ref'): if len(arg) == 4: referredPageTitle = wikipedia.input(u'Links to which page should be processed?') else: referredPageTitle = arg[5:] referredPage = wikipedia.Page(wikipedia.getSite(), referredPageTitle) gen = pagegenerators.ReferringPageGenerator(referredPage) elif arg.startswith('-links'): if len(arg) == 6: linkingPageTitle = wikipedia.input(u'Links from which page should be processed?') else: linkingPageTitle = arg[7:] linkingPage = wikipedia.Page(wikipedia.getSite(), linkingPageTitle) gen = pagegenerators.LinkedPageGenerator(linkingPage) elif arg.startswith('-start'): if len(arg) == 6: firstPageTitle = wikipedia.input(u'Which page do you want to chage?') else: firstPageTitle = arg[7:] namespace = wikipedia.Page(wikipedia.getSite(), firstPageTitle).namespace() gen = pagegenerators.AllpagesPageGenerator(firstPageTitle, namespace) elif arg.startswith('-google'): if len(arg) >= 8: googleQuery = arg[8:] gen = pagegenerators.GoogleSearchPageGenerator(googleQuery) elif arg.startswith('-except:'): exceptions.append(arg[8:]) elif arg.startswith('-fix:'): fix = arg[5:] elif arg == '-always': acceptall = True elif arg.startswith('-namespace:'): namespaces.append(int(arg[11:])) else: commandline_replacements.append(arg) if (len(commandline_replacements) == 2 and fix == None): replacements.append((commandline_replacements[0], commandline_replacements[1])) wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg ) % ' (-' + commandline_replacements[0] + ' +' + commandline_replacements[1] + ')') elif fix == None: old = wikipedia.input(u'Please enter the text that should be replaced:') new = wikipedia.input(u'Please enter the new text:') change = '(-' + old + ' +' + new replacements.append((old, new)) while True: old = wikipedia.input(u'Please enter another text that should be replaced, or press Enter to start:') if old == '': change = change + ')' break new = wikipedia.input(u'Please enter the new text:') change = change + ' & -' + old + ' +' + new replacements.append((old, new)) default_summary_message = wikipedia.translate(wikipedia.getSite(), 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_message == '': summary_message = default_summary_message wikipedia.setAction(summary_message) else: # Perform one of the predefined actions. try: fix = fixes[fix] except KeyError: wikipedia.output(u'Available predefined fixes are: %s' % fixes.keys()) wikipedia.stopme() sys.exit() if fix.has_key('regex'): regex = fix['regex'] if fix.has_key('msg'): wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), fix['msg'])) if fix.has_key('exceptions'): exceptions = fix['exceptions'] replacements = fix['replacements'] # already compile all regular expressions here to save time later for i in range(len(replacements)): old, new = replacements[i] if not regex: old = re.escape(old) oldR = re.compile(old, re.UNICODE) replacements[i] = oldR, new for i in range(len(exceptions)): exception = exceptions[i] if not regex: exception = re.escape(exception) exceptionR = re.compile(exception, re.UNICODE) exceptions[i] = exceptionR if xmlFilename: gen = XmlDumpReplacePageGenerator(xmlfilename, replacements, exceptions) elif useSql: whereClause = 'WHERE (%s)' % ' OR '.join(["old_text RLIKE '%s'" % prepareRegexForMySQL(old.pattern) for (old, new) in replacements]) if exceptions: exceptClause = 'AND NOT (%s)' % ' OR '.join(["old_text RLIKE '%s'" % prepareRegexForMySQL(exc.pattern) for exc in exceptions]) else: exceptClause = '' query = u"""
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.compile('.*<div id\=\"bodyContent\">.*') rFooter = re.compile('.*<div id\=\"footer\">.*') rDivOpen = re.compile('.*<div ') rDivClose = re.compile('.*<\/div>.*') divLevel = 0 divLast = -1 inArticle = 0 inFooter = 0 result = {'article':"", 'footer':""} for line in s: if rDivOpen.match(line): divLevel = divLevel + 1 if rBody.match(line): inArticle = 1 divLast = divLevel-1 elif rFooter.match(line): divLast = divLevel-1 inFooter = 1 if inArticle: result['article'] += line elif inFooter: result['footer'] += line if rDivClose.match(line): divLevel = divLevel - 1 if divLevel == divLast: inArticle = 0 inFooter = 0 divLast = -1 return result
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 debug: print "--------------------------------------------------" if debug: print "Found image: %s"% imageTitle # need to strip off "Afbeelding:", "Image:" etc. # we only need the substring following the first colon filename = sourceImagePage.title().split(":", 1)[1] # Spaces might occur, but internally they are represented by underscores. # Change the name now, because otherwise we get the wrong MD5 hash. filename = filename.replace(' ', '_') # Also, the first letter should be capitalized # TODO: Don't capitalize on non-capitalizing wikis filename = filename[0].upper()+filename[1:] if debug: print "Image filename is: %s " % filename encodedFilename = filename.encode(sourceSite.encoding()) md5sum = md5.new(encodedFilename).hexdigest() if debug: print "MD5 hash is: %s" % md5sum encodedFilename = urllib.quote(encodedFilename) # TODO: This probably doesn't work on all wiki families url = 'http://%s/upload/%s/%s/%s' % (sourceSite.hostname(), md5sum[0], md5sum[:2], encodedFilename) print "URL should be: %s" % url # localize the text that should be printed on the image description page try: description = sourceImagePage.get() # try to translate license templates if licenseTemplates.has_key((sourceSite.sitename(), self.targetSite.sitename())): for old, new in licenseTemplates[(sourceSite.sitename(), self.targetSite.sitename())].iteritems(): new = '{{%s}}' % new old = re.compile('{{%s}}' % old) description = wikipedia.replaceExceptNowikiAndComments(description, old, new) description = wikipedia.translate(self.targetSite, copy_message) % (sourceSite, description) # TODO: Only the page's version history is shown, but the file's # version history would be more helpful description += '\n\n' + sourceImagePage.getVersionHistoryTable() # add interwiki link if sourceSite.family == self.targetSite.family: description += "\r\n\r\n" + sourceImagePage.aslink(forceInterwiki = True) except wikipedia.NoPage: description='' print "Image does not exist or description page is empty." except wikipedia.IsRedirectPage: description='' print "Image description page is redirect." else: bot = upload.UploadRobot(url = url, description = description, targetSite = self.targetSite, urlEncoding = sourceSite.encoding()) # try to upload targetFilename = bot.run() if targetFilename and self.targetSite.family.name == 'commons' and self.targetSite.lang == 'commons': # upload to Commons was successful reason = wikipedia.translate(sourceSite, nowCommonsMessage) # try to delete the original image if we have a sysop account if config.sysopnames.has_key(sourceSite.family.name) and config.sysopnames[sourceSite.family.name].has_key(sourceSite.lang): if sourceImagePage.delete(reason): return if nowCommonsTemplate.has_key(sourceSite.lang) and config.usernames.has_key(sourceSite.family.name) and config.usernames[sourceSite.family.name].has_key(sourceSite.lang): # add the nowCommons template. wikipedia.output(u'Adding nowCommons template to %s' % sourceImagePage.title()) sourceImagePage.put(original_description + '\n\n' + nowCommonsTemplate[sourceSite.lang] % targetFilename, comment = nowCommonsMessage[sourceSite.lang])
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 line in f.readlines(): m=R.match(line) if m: sa.append(string.replace(m.group(1), " ", "_")) else: print "ERROR: Did not understand %s line:\n%s" % ( arg[6:], repr(line)) f.close() elif arg.startswith("-o:"): output_directory = arg[3:] elif arg.startswith("-images"): save_images = True elif arg.startswith("-overwrite:"): if arg[11] == "I": overwrite_images = True elif arg[11] == "A": overwrite_articles = True elif arg[11] == "B": overwrite_images = True overwrite_articles = True else: sa.append(arg.replace(" ", "_")) headers = {"Content-type": "application/x-www-form-urlencoded", "User-agent": "RobHooftWikiRobot/1.0"} print "opening connection to", mysite.hostname(), conn = httplib.HTTPConnection(mysite.hostname()) print " done" R = re.compile('.*/wiki/(.*)') data = "" for article in sa: filename = article.replace("/", "_") if os.path.isfile(output_directory + filename + ".txt") and overwrite_articles == False: print "skipping " + article continue data = "" ua = article while len(data) < 2: url = '/wiki/'+ ua conn.request("GET", url, "", headers) response = conn.getresponse() data = response.read() if len(data) < 2: print ua + " failed. reading", result = R.match(response.getheader("Location", )) ua = result.group(1) print ua data = extractArticle(data) f = open (output_directory + filename + ".txt", 'w') f.write (data['article'] + '\n' + data['footer']) f.close() print "saved " + article if save_images: images = extractImages(data['article']) for i in images: if overwrite_images == False and os.path.isfile(output_directory + i['image']): print "skipping existing " + i['image'] continue print 'downloading ' + i['image'], uo = wikipedia.MyURLopener() file = uo.open( "http://upload.wikimedia.org/wikipedia/" +mysite.lang + '/' + i['path'] + i['image']) content = file.read() if (len(content) < 500): uo.close() print "downloading from commons", uo = wikipedia.MyURLopener() file = uo.open( "http://commons.wikimedia.org/upload/" + i['path'] + i['image']) #print "http://commons.wikimedia.org/upload/", i['path'] , i['image'], file content = file.read() f = open(output_directory + i['image'], "wb") f.write(content) f.close() print "\t\t", (len(content)/1024), "KB done" conn.close()
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 for pl in self.pending: # Mark the page as done self.done[pl] = pl.site()
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 for pl in self.pending: # Mark the page as done self.done[pl] = pl.site()
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 allowed to touch categories on the German Wikipedia. See de.wikipedia.org/wiki/Wikipedia_Diskussion:Personendaten#Position') s = categoryFormat(new, insite = site) s2 = removeCategoryLinks(oldtext, site = site) if s: if site.language() in site.family.category_attop: newtext = s + site.family.category_text_separator + s2 else: # calculate what was after the categories links on the page firstafter = 0 try: while s2[firstafter-1] == oldtext[firstafter-1]: firstafter -= 1 except IndexError: pass # Is there any text in the 'after' part that means we should keep it after? if "</noinclude>" in s2[firstafter:]: newtext = s2[:firstafter+1] + s + s2[firstafter+1:] elif site.language() in site.family.categories_last: newtext = s2 + site.family.category_text_separator + s else: interwiki = getLanguageLinks(s2) s2 = removeLanguageLinks(s2, site) + site.family.category_text_separator + s newtext = replaceLanguageLinks(s2, interwiki, site) else: return s2 return newtext
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. """ content_type, body = encode_multipart_formdata(fields, files) conn = httplib.HTTPConnection(host) conn.putrequest('POST', selector) conn.putheader('content-type', content_type) conn.putheader('content-length', str(len(body))) conn.putheader("User-agent", "RobHooftWikiRobot/1.0") conn.putheader('Host', host) if cookies: conn.putheader('Cookie',cookies) conn.endheaders() conn.send(body) response = conn.getresponse() returned_html = response.read() conn.close() return response, returned_html
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: self.targetSite = targetSite or wikipedia.getSite() self.targetSite.forceLogin()
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 = newDescription
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.url: uo = wikipedia.MyURLopener() file = uo.open(self.url,"rb") else: # Opening local files with MyURLopener would be possible, but we # don't do it because it only accepts ASCII characters in the # filename. file = open(self.url,"rb") wikipedia.output(u'Reading file %s' % self.url) contents = file.read() if contents.find("The requested URL was not found on this server.") != -1: print "Couldn't download the image." return file.close() # Isolate the pure name filename = self.url if '/' in filename: filename = filename.split('/')[-1] if '\\' in filename: filename = filename.split('\\')[-1] if self.urlEncoding: filename = urllib.unquote(filename) filename = filename.decode(self.urlEncoding) if not self.keepFilename: wikipedia.output(u"The filename on the target wiki will default to: %s" % filename) # ask newfn until it's valid ok = False # FIXME: these 2 belong somewhere else, presumably in family forbidden = '/' # to be extended allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi', u'ogg', u'png', u'svg', u'xcf') while not ok: ok = True newfn = wikipedia.input(u'Enter a better name, or press enter to accept:') if newfn == "": newfn = filename ext = os.path.splitext(newfn)[1].lower().strip('.') for c in forbidden: if c in newfn: print "Invalid character: %s. Please try again" % c ok = False if ext not in allowed_formats and ok: choice = wikipedia.inputChoice(u"File format is not %s but %s. Continue [y/N]? " % (allowed_formats, ext)) if choice == 'n': ok = False if newfn != '': filename = newfn # MediaWiki doesn't allow spaces in the file name. # Replace them here to avoid an extra confirmation form filename = filename.replace(' ', '_') # Convert the filename (currently Unicode) to the encoding used on the # target wiki encodedFilename = filename.encode(self.targetSite.encoding()) # A proper description for the submission. wikipedia.output(u"The suggested description is:") wikipedia.output(self.description) 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 user saved / didn't press Cancel if newDescription: self.description = newDescription formdata = {} formdata["wpUploadDescription"] = self.description
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, keepFilename) bot.run()
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, keepFilename) bot.run()
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: Number of pages queued is %d, trying to add %d more."%(len(self.subjects), number) for i in range(number): try: while True: page = self.pageGenerator.next() if page in globalvar.skip: wikipedia.output(u'Skiping: %s is in the skip list' % page) continue if globalvar.skipauto: dictName, year = date.getDictionaryYear(page.site().language(), page.title()) if dictName != None: wikipedia.output(u'Skiping: %s is auto entry %s(%s)' % (page.title(),dictName,year)) continue break
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 pages where self is used as a template. * onlyTemplateInclusion - if True, only returns pages where self is used as a template. """ site = self.site() path = site.references_address(self.urlname()) output(u'Getting references to %s' % self.aslink()) delay = 1 refTitles = set() # use a set to avoid duplications redirTitles = set()
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 pages where self is used as a template. * onlyTemplateInclusion - if True, only returns pages where self is used as a template. """ site = self.site() path = site.references_address(self.urlname()) output(u'Getting references to %s' % self.aslink()) delay = 1 refTitles = set() # use a set to avoid duplications redirTitles = set()
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(description) bot = UploadRobot(filename, description, wiki, keep) bot.run()
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(description) bot = UploadRobot(filename, description, wiki, keep) bot.run()
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(description) bot = UploadRobot(filename, description, wiki, keep) bot.run()
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.myencoding()) ignore_title_regexes.append(re.compile(ig)) for Rignore in ignore_title_regexes: # run backwards because we might remove list items for i in range(len(refs)-1, -1, -1): if Rignore.match(refs[i]): wikipedia.output('Ignoring page ' + refs[i], wikipedia.myencoding()) del refs[i] refpls = [] for ref in refs: refpl = wikipedia.PageLink(self.disambPl.site(), ref) if not self.primaryIgnoreManager.isIgnored(refpl): refpls.append(refpl) return refpls
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 = wikipedia.Page(wikipedia.getSite(), pageTitle) gen = iter([page]) gen = pagegenerators.PreloadingGenerator(gen, pageNumber = 240) gen = pagegenerators.RedirectFilterPageGenerator(gen) bot = WeblinkCheckerRobot(gen) try: bot.run() finally: waitTime = 0 # Don't wait longer than 30 seconds for threads to finish. while threading.activeCount() > 2 and waitTime < 30: wikipedia.output(u"Waiting for remaining %i threads to finish, please wait..." % (threading.activeCount() - 2)) # don't count the main thread and report thread # wait 1 second time.sleep(1) waitTime += 1 if threading.activeCount() > 2: wikipedia.output(u'Remaining %i thread will be killed.' % (threading.activeCount() - 2)) # Threads will die automatically because they are daemonic. wikipedia.output(u'Saving history...') bot.history.save() if bot.history.reportThread: bot.history.reportThread.shutdown() # wait until the report thread is shut down. while bot.history.reportThread.isAlive(): time.sleep(0.1) #else: # Killing the daemonic threads might lag, so we wait some time. # time.sleep(1.0)
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 = wikipedia.Page(wikipedia.getSite(), pageTitle) gen = iter([page]) gen = pagegenerators.PreloadingGenerator(gen, pageNumber = 240) gen = pagegenerators.RedirectFilterPageGenerator(gen) bot = WeblinkCheckerRobot(gen) try: bot.run() finally: waitTime = 0 # Don't wait longer than 30 seconds for threads to finish. while threading.activeCount() > 2 and waitTime < 30: wikipedia.output(u"Waiting for remaining %i threads to finish, please wait..." % (threading.activeCount() - 2)) # don't count the main thread and report thread # wait 1 second time.sleep(1) waitTime += 1 if threading.activeCount() > 2: wikipedia.output(u'Remaining %i thread will be killed.' % (threading.activeCount() - 2)) # Threads will die automatically because they are daemonic. wikipedia.output(u'Saving history...') bot.history.save() if bot.history.reportThread: bot.history.reportThread.shutdown() # wait until the report thread is shut down. while bot.history.reportThread.isAlive(): time.sleep(0.1) #else: # Killing the daemonic threads might lag, so we wait some time. # time.sleep(1.0)
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 webservers block # unknown clients self.header = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050511 Firefox/1.0.4 SUSE/1.0.4-0.3'}
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.check() else: # TODO: HTTPS try: conn = httplib.HTTPConnection(self.host) except httplib.error, arg: return False, u'HTTP Error: %s' % arg try: conn.request('GET', '%s%s' % (self.path, self.query), None, self.header) except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL' try: response = conn.getresponse() except Exception, arg: return False, u'Error: %s' % arg #wikipedia.output('%s: %s' % (self.url, response.status)) # site down if the server status is between 400 and 499 siteDown = response.status in range(400, 500) return not siteDown, '%s %s' % (response.status, response.reason)
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 catContentDB[supercat][0] else: subcatlist = supercat.subcategories() articlelist = supercat.articles() # add to dictionary catContentDB[cat] = [subcatlist, articlelist] return subcatlist
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 = mylang) s2 = removeLanguageLinks(oldtext) if s: if mylang in config.interwiki_atbottom: newtext = s2 + config.interwiki_text_separator + s else: newtext = s + config.interwiki_text_separator + s2 else: newtext = s2 return newtext
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 target of the string. """ if not links: return '' s = [] ar = links.keys() ar.sort() if mylang in interwiki_putfirst: #In this case I might have to change the order ar2 = [] for code in interwiki_putfirst[mylang]: if code in ar: del ar[ar.index(code)] ar2 = ar2 + [code] ar = ar2 + ar for code in ar: try: s.append(links[code].aslink()) except AttributeError: s.append('[[%s:%s]]' % (code, links[code])) s=config.interwiki_langs_separator.join(s) + '\r\n' return unicodeName(s, language = incode)
'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 target of the string. """ if not links: return '' s = [] ar = links.keys() ar.sort() if mylang in interwiki_putfirst: #In this case I might have to change the order ar2 = [] for code in interwiki_putfirst[mylang]: if code in ar: del ar[ar.index(code)] ar2 = ar2 + [code] ar = ar2 + ar for code in ar: try: s.append(links[code].aslink()) except AttributeError: s.append('[[%s:%s]]' % (code, links[code])) s=config.interwiki_langs_separator.join(s) + '\r\n' return unicodeName(s, language = incode)
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 target of the string. """ if not links: return '' s = [] ar = links.keys() ar.sort() if mylang in interwiki_putfirst: #In this case I might have to change the order ar2 = [] for code in interwiki_putfirst[mylang]: if code in ar: del ar[ar.index(code)] ar2 = ar2 + [code] ar = ar2 + ar for code in ar: try: s.append(links[code].aslink()) except AttributeError: s.append('[[%s:%s]]' % (code, links[code])) s=config.interwiki_langs_separator.join(s) + '\r\n' return unicodeName(s, language = incode)
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 "url2link", repr(x), "same encoding",incode,code return unicode2html(x, encoding = code2encoding(code)) else: #print "url2link", repr(x), "different encoding" return unicode2html(x, encoding = 'ascii')