rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
newcat = wikipedia.input('Category to add (do not give namespace) : ', encode = True) newcat = newcat
newcat = wikipedia.input('Category to add (do not give namespace) : ')
def add_category(): 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...
if othersite and othersite.lang == self.lang:
if othersite and othersite.lang != self.lang:
def linkto(self, linkname, othersite = None): if othersite and othersite.lang == self.lang: return '[[%s:%s]]' % (self.lang, linkname) else: return '[[%s]]' % linkname
self.problem('Someone refers to %s with us' % pl.asasciilink())
self.problem(err)
def assemble(self, returnonquestion = False, askall = False): new = {} for pl in self.done.keys(): code = pl.code() if code == wikipedia.mylang and pl.exists() and not pl.isRedirectPage() and not pl.isEmpty(): if pl != self.inpl: if returnonquestion: return None self.problem('Someone refers to %s with us' % pl.asasciil...
self.problem("'%s' as well as '%s'" % (new[code].asasciilink(), pl.asasciilink()))
self.problem(err)
def assemble(self, returnonquestion = False, askall = False): new = {} for pl in self.done.keys(): code = pl.code() if code == wikipedia.mylang and pl.exists() and not pl.isRedirectPage() and not pl.isEmpty(): if pl != self.inpl: if returnonquestion: return None self.problem('Someone refers to %s with us' % pl.asasciil...
gen = pagegenerators.TextfileGenerator(filename)
gen = pagegenerators.TextfilePageGenerator(filename)
def main(): # if -file is not used, this temporary array is used to read the page title. pageTitle = [] page = None gen = None interwiki = False targetLang = None targetFamily = None for arg in sys.argv[1:]: #for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'imagetransfer') if arg: if arg == '-interwiki': inte...
file = uo.open(self.url)
file = uo.open(self.url,"rb")
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...
file = open(self.url)
file = open(self.url,"rb")
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...
refresh_messages()
refresh_messages(lang)
def get(key, lang = None): if lang == None: lang = wikipedia.mylang try: # find out how old our saved dump is (in seconds) file_age = time.time() - os.path.getmtime('mediawiki-messages/mediawiki-messages-%s.dat' % lang) # if it's older than 1 month, reload it if file_age > 30 * 24 * 60 * 60: print 'Current MediaWiki me...
wikipedia.output("%3d - %s" % (i, alternatives[i]))
wikipedia.output("%3d - %s" % (i, alternatives[i]), wikipedia.myencoding())
def makepath(path): """ creates missing directories for the given path and returns a normalized absolute version of the path. - if the given path already exists in the filesystem the filesystem is not modified. - otherwise makepath creates directories along the given path using the dirname() of the path. You may appe...
if ignore_title.has_key(self.mylang): ignore_title[self.mylang] += self.mysite.namespaces() else: ignore_title[self.mylang] = self.mysite.namespaces()
if not ignore_title.has_key(self.mylang): ignore_title[self.mylang] = [] ignore_title[self.mylang] += [u'%s:' % namespace for namespace in self.mysite.namespaces()]
def run(self): if self.main_only: if ignore_title.has_key(self.mylang): ignore_title[self.mylang] += self.mysite.namespaces() else: ignore_title[self.mylang] = self.mysite.namespaces() for disambTitle in self.page_list: # when run with -redir argument, there's another summary message if self.solve_redirect: wikipedia....
address = self.site().delete_address(space2underline(self.title()))
address = self.site().delete_address(self.urlname())
def delete(self, reason = None, prompt = True): """Deletes the page from the wiki. Requires administrator status. If reason is None, asks for a reason. If prompt is True, asks the user if he wants to delete the page. """ # TODO: Find out if bot is logged in with an admin account, raise exception # or show error message...
catlib.change_category(article, original_cat.titleWithoutNamespace(), current_cat.titleWithoutNamespace())
catlib.change_category(article, original_cat, current_cat.titleWithoutNamespace())
def move_to_category(self, article, original_cat, current_cat): ''' Given an article which is in category original_cat, ask the user if it should be moved to one of original_cat's subcategories. Recursively run through subcategories' subcategories. NOTE: current_cat is only used for internal recursion. You should alway...
Rredir = re.compile('\<li\>\<a href=".+?" title=(.*?)">')
Rredir = re.compile('\<li\>\<a href=".+?" title="(.*?)">')
def retrieve_double_redirects(self): if self.source == None: mysite = wikipedia.getSite() # retrieve information from the live wiki's maintenance page host = mysite.hostname() # double redirect maintenance page's URL url = mysite.double_redirects_address(default_limit = False) print 'Retrieving special page...' mainte...
findTemplate=re.compile(ur'\{\{[Cc]ommons\}\}')
findTemplate=re.compile(ur'\{\{[Cc]ommons')
def run(self): for page in self.generator: try: wikipedia.output(u'\n>>>> %s <<<<' % page.title()) commons = wikipedia.Site('commons', 'commons') commonspage = wikipedia.Page(commons, page.title()) try: getcommons = commonspage.get(get_redirect=True) if page.title() == commonspage.title(): oldText = page.get() text = o...
name=[]
inname=[]
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
name.append(arg) name='_'.join(name) if not name: name=raw_input('Which page to check:') name=wikipedia.link2url(name) m=treesearch(mylang,name)
inname.append(arg) inname='_'.join(inname) if not inname: inname=raw_input('Which page to check:') inname=wikipedia.link2url(inname) m=treesearch(mylang,inname)
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
old=None
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
if m[code,cname]: old=wikipedia.getLanguageLinks(m[code,cname]) oldtext=m[code,cname]
pass
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
print "NOTE: Replacing %s: %s"%(mylang,name)
print "NOTE: Replacing %s: %s"%(mylang,inname)
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
status,reason,data=wikipedia.putPage(mylang,name,newtext)
status,reason,data=wikipedia.putPage(mylang,inname,newtext)
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
except wikipedia.NoPage:
def showImageList(self, imagelist): for i in range(len(imagelist)): image = imagelist[i] print "-"*60 wikipedia.output(u"%s. Found image: %s"% (i, image.aslink())) try: # Show the image description page's contents wikipedia.output(image.get(throttle=False)) except wikipedia.NoPage: try: # Maybe the image is on the targ...
except wikipedia.IsRedirectPage: print "Description page is redirect?!"
except wikipedia.IsRedirectPage: print "Description page is redirect?!" except wikipedia.NoPage: break
def showImageList(self, imagelist): for i in range(len(imagelist)): image = imagelist[i] print "-"*60 wikipedia.output(u"%s. Found image: %s"% (i, image.aslink())) try: # Show the image description page's contents wikipedia.output(image.get(throttle=False)) except wikipedia.NoPage: try: # Maybe the image is on the targ...
catlib.change_category(article, original_cat.titleWithoutNamespace(), None)
catlib.change_category(article, original_cat, None)
def move_to_category(self, article, original_cat, current_cat): ''' Given an article which is in category original_cat, ask the user if it should be moved to one of original_cat's subcategories. Recursively run through subcategories' subcategories. NOTE: current_cat is only used for internal recursion. You should alway...
reftxt = re.sub(boilerplateR, '{{subst:' + unicode(old, 'iso-8859-1') + '}}', reftxt)
reftxt = re.sub(boilerplateR, '{{subst:' + old + '}}', reftxt)
def treat(refpl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: pass else: # Check if boilerplate is really used in this article if not boilerplateR.search(reftxt): print "Not found in %s"%refpl return # Replace all occurences of the boilerplate in this article if resolve: reftxt = re.sub(boilerplateR, '{{s...
reftxt = re.sub(boilerplateR, '{{msg:' + unicode(new, 'iso-8859-1') + '}}', reftxt)
reftxt = re.sub(boilerplateR, '{{msg:' + new + '}}', reftxt)
def treat(refpl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: pass else: # Check if boilerplate is really used in this article if not boilerplateR.search(reftxt): print "Not found in %s"%refpl return # Replace all occurences of the boilerplate in this article if resolve: reftxt = re.sub(boilerplateR, '{{s...
reftxt = re.sub(boilerplateR, '{{' + unicode(new, 'iso-8859-1') + '}}', reftxt)
reftxt = re.sub(boilerplateR, '{{' + new + '}}', reftxt)
def treat(refpl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: pass else: # Check if boilerplate is really used in this article if not boilerplateR.search(reftxt): print "Not found in %s"%refpl return # Replace all occurences of the boilerplate in this article if resolve: reftxt = re.sub(boilerplateR, '{{s...
print '%d' % len(getReferences(thispl)) sys.exit()
def treat(refpl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: pass else: # Check if boilerplate is really used in this article if not boilerplateR.search(reftxt): print "Not found in %s"%refpl return # Replace all occurences of the boilerplate in this article if resolve: reftxt = re.sub(boilerplateR, '{{s...
'YearAD' : (lambda v: 0<=v and v<2051, 0,2051),
'YearAD' : (lambda v: 0<=v and v<2501, 0,2501),
def makeMonthNamedList( lang, pattern, makeUpperCase = None ): """Creates a list of 12 elements based on the name of the month. The language-dependent month name is used as a formating argument to the pattern. The pattern must be have one %s that will be replaced by the localized month name. Use %%d for any other param...
'DecadeAD' : (lambda v: 0<=v and v<2051, 0,2051),
'DecadeAD' : (lambda v: 0<=v and v<2501, 0,2501),
def makeMonthNamedList( lang, pattern, makeUpperCase = None ): """Creates a list of 12 elements based on the name of the month. The language-dependent month name is used as a formating argument to the pattern. The pattern must be have one %s that will be replaced by the localized month name. Use %%d for any other param...
def assemblesecondrun(self, previous, askall):
def assemblesecondrun(self, previous, askall=False):
def assemblesecondrun(self, previous, askall): new = previous askit = askall for pl in self.done.keys(): code = pl.code() if code == wikipedia.mylang and pl.exists() and not pl.isRedirectPage() and not pl.isEmpty(): pass elif pl.exists() and not pl.isRedirectPage(): if new.has_key(code): pass elif code in ('zh-tw','zh-...
predata.append(('wpMinorEdit', '1'))
predata.append(('wpMinoredit', '1'))
def putPage(code, name, text, comment = None, watchArticle = False, minorEdit = True, newPage = False): """Upload 'text' on page 'name' to the 'code' language wikipedia. Use of this routine can normally be avoided; use PageLink.put instead. """ import httplib put_throttle() host = family.hostname(code) address = family...
ask = wikipedia.input('What do you do: (c)hange page name, (n)ext page or (q)uit?')
ask = wikipedia.input('What do you do: (c)hange page name (a)ppend to page name, (n)ext page or (q)uit?')
def Movepages(page, deletedPages): 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 in ['c', 'C']: pagemove = wikipedia.input(u'New page name:') titleroot = wikipedia.Page(wikipedia.getSite(), pagetitle) m...
def change_category(article, oldCat, newCatTitle):
def change_category(article, oldCat, newCatTitle, comment=None):
def change_category(article, oldCat, newCatTitle): """ Given an article which is in category oldCat, moves it to category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the category...
for cat in cats:
for cat in cats[:]:
def change_category(article, oldCat, newCatTitle): """ Given an article which is in category oldCat, moves it to category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the category...
article.put(text)
article.put(text, comment)
def change_category(article, oldCat, newCatTitle): """ Given an article which is in category oldCat, moves it to category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the category...
R=re.compile("[(HREF)(href)]=[\"'](.*?)[\"']")
R=re.compile("[\"'](.*?)[\"']")
def get_imagelinks(url): # Given a URL, get all images linked to by the page at that URL. # First, we get the location for relative links from the URL. relativepath = url.split("/") if len(relativepath) == 1: relativepath=relativepath[0] else: relativepath=relativepath[:len(relativepath)-1] relativepath="/".join(relati...
fileformats = ('jpg', 'jpeg', 'png', 'gif', 'svg', 'ogg')
def main(give_url,image_url): url = give_url fileformats = ('jpg', 'jpeg', 'png', 'gif', 'svg', 'ogg') basicdesc = [] mysite = wikipedia.getSite() if not mysite.loggedin(): print "You must be logged in to upload images" import sys sys.exit(1) if url == '': if image_url: url = wikipedia.input(u"What URL range should I...
mysite = wikipedia.getSite()
def main(give_url,image_url): url = give_url fileformats = ('jpg', 'jpeg', 'png', 'gif', 'svg', 'ogg') basicdesc = [] mysite = wikipedia.getSite() if not mysite.loggedin(): print "You must be logged in to upload images" import sys sys.exit(1) if url == '': if image_url: url = wikipedia.input(u"What URL range should I...
except:
finally:
def main(give_url,image_url): url = give_url fileformats = ('jpg', 'jpeg', 'png', 'gif', 'svg', 'ogg') basicdesc = [] mysite = wikipedia.getSite() if not mysite.loggedin(): print "You must be logged in to upload images" import sys sys.exit(1) if url == '': if image_url: url = wikipedia.input(u"What URL range should I...
raise else: raise
def main(give_url,image_url): url = give_url fileformats = ('jpg', 'jpeg', 'png', 'gif', 'svg', 'ogg') basicdesc = [] mysite = wikipedia.getSite() if not mysite.loggedin(): print "You must be logged in to upload images" import sys sys.exit(1) if url == '': if image_url: url = wikipedia.input(u"What URL range should I...
except UnicodeEncodeError:
except UnicodeError:
def link2url(name, code, incode = None): """Convert an interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link""" if code == 'eo': name = name.replace('cx','&#265;') name = name.replace('Cx','&#264;') name = name.replace('CX','&#264;') name = nam...
if newtext[0]=='=':
if newtext=='': pass elif newtext[0]=='=':
def get_image(fn, target, description, debug=False): uploadaddr='/wiki/%s:Upload'%wikipedia.special[wikipedia.mylang] # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = file.read() file.close() # Isolate the pure name if '/' in fn: fn = fn.split('/')[-1] if '\\' in fn: fn = fn.split('\\')[-1...
preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = ReplaceRobot(gen, replacements, exceptions, regex, acceptall)
preloadingGen = pagegenerators.PreloadingGenerator(gen, pageNumber = 20) bot = ReplaceRobot(preloadingGen, replacements, exceptions, regex, acceptall)
def main(): # How we want to retrieve information on which pages need to be changed. # Can either be 'sqldump', 'textfile' or 'userinput'. source = None # Array which will collect commandline parameters. # First element is original text, second element is replacement text. commandline_replacements = [] # A dictionary w...
for site in updatedSites: del new[site] self.reportBacklinks(new)
self.reportBacklinks(new, updatedSites)
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.
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed."""
def reportBacklinks(self, new, updatedSites): """ Report missing back links. This will be called from finish() if needed. updatedSites is a list that contains all sites we changed, to avoid reporting of missing backlinks for pages we already fixed """
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site, page in new.iteritems(): if not page.section(): shouldlink = new.values() + [self.inpl] linked = page.interwiki() for xpage in shouldlink: if xpage != page and not xpage in linked: for l in linke...
if not page.section():
if site not in updatedSites and not page.section():
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site, page in new.iteritems(): if not page.section(): shouldlink = new.values() + [self.inpl] linked = page.interwiki() for xpage in shouldlink: if xpage != page and not xpage in linked: for l in linke...
replacements[i] = exceptionR
exceptions[i] = exceptionR
def main(): gen = None # How we want to retrieve information on which pages need to be changed. # Can either be 'xmldump', 'textfile' or 'userinput'. source = None # Array which will collect commandline parameters. # First element is original text, second element is replacement text. commandline_replacements = [] # A l...
result.append(self.__class__(self.code(), linkname=catname))
result.append(self.__class__(self.code(), title = catname))
def categories(self): """A list of categories that the article is in. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
newtext = s2[:firstafter+1] + s + s2[firstafter+1:]
newtext = s2[:firstafter] + s + s2[firstafter:]
def replaceCategoryLinks(oldtext, new, site = None): """Replace the category links given in the wikitext given in oldtext by the new links given in new. 'new' should be a list of Category objects. """ if site is None: site = getSite() if site == Site('de', 'wikipedia'): raise Error('The PyWikipediaBot is no longer al...
return Page(self,self.namespace(14)+':'+self.family.disambcatname[self.lang])
return catlib.Category(self,self.namespace(14)+':'+self.family.disambcatname[self.lang])
def disambcategory(self): try: return Page(self,self.namespace(14)+':'+self.family.disambcatname[self.lang]) except KeyError: raise NoPage
if wikipedia.isInterwikiLink(m.group('title')):
if m.group('title') == '' or 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. """
print "%s already has %s"%(pl.aslocallink(),catpl.aslocallink())
print "%s already has %s"%(pl2.aslocallink(),catpl.aslocallink())
def add_category(): 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...
Rsupercat = re.compile('title=.*\"([^\"]*)\"')
Rsupercat = re.compile('title ="([^"]*)"')
def _make_catlist(self, recurse = False): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and categories of any subcategories are also retrieved.
supercats.append(title)
if iscattitle(title): supercats.append(title)
def _make_catlist(self, recurse = False): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and categories of any subcategories are also retrieved.
(pages, supercats) = self.catlist()
supercats = [] for title in self.catlist(recurse)[1]: ncat = _CatLink(self.code(), title) supercats.append(ncat)
def supercategories(self, recurse = False): """Create a list of all subcategories of the current category.
if m and not get_redirect: output(u"DBG> %s is redirect to %s" % (self.title(), m.group(1))) raise IsRedirectPage(m.group(1))
if m: if get_redirect: self._redirarg = m.group(1) else: output(u"DBG> %s is redirect to %s" % (self.title(), m.group(1))) raise IsRedirectPage(m.group(1))
def getEditPage(self, get_redirect=False, throttle = True, sysop = False): """ Get the contents of the Page via the edit page. Do not use this directly, use get() instead. Arguments: get_redirect - Get the contents, even if it is a redirect page This routine returns a unicode string containing the wiki text. """ isW...
if not trailingChars or label:
if not (trailingChars or label):
def cleanUpLinks(self, text): trailR = re.compile(self.site.linktrail()) # The regular expression which finds links. Results consist of four groups: # group title is the target page title, that is, everything before | or ]. # group section is the page section. It'll include the # to make life easier for us. # group lab...
lines = text.split('\n')
lines = text.split('\r\n')
def removeUselessSpaces(self, text): result = [] multipleSpacesR = re.compile(' +') spaceAtLineEndR = re.compile(' $') preR = re.compile('<pre', re.IGNORECASE) lines = text.split('\n') for line in lines: if len(line) > 0 and line[0] != ' ' and not preR.search(line): line = wikipedia.replaceExceptMathNowikiAndComments(...
return '\n'.join(result)
return '\r\n'.join(result)
def removeUselessSpaces(self, text): result = [] multipleSpacesR = re.compile(' +') spaceAtLineEndR = re.compile(' $') preR = re.compile('<pre', re.IGNORECASE) lines = text.split('\n') for line in lines: if len(line) > 0 and line[0] != ' ' and not preR.search(line): line = wikipedia.replaceExceptMathNowikiAndComments(...
+ "(0.[\d\.]+?),"
+ "([\d\.]+?),"
def entries(self): ''' Generator which reads one line at a time from the SQL dump file, and parses it to create SQLentry objects. Stops when the end of file is reached. ''' # This regular expression will match one SQL database entry (i.e. a # page), and each group represents an attribute of that entry. # NOTE: We don't...
s.append(('Jaren: '+'[[%d]] -- '*5+"'''%d'''"+' -- [[%d]]'*5)%tuple(range(year-5,year+6)))
s.append(('Jaren: '+'[[%s]] -- '*5+"'''%s'''"+' -- [[%s]]'*5)%ymap(range(year-5,year+6)))
def header(year): s=[] cent=(int(year)-1)/100+1 s.append('<!-- robot -->') s.append('<table align=center><tr><td align=center>') s.append("[[Eeuwen]]: [[%de eeuw]] -- '''[[%de eeuw]]''' -- [[%de eeuw]]"%tuple(range(cent-1,cent+2))) s.append('</td></tr><tr><td align=center>') s.append(('Jaren: '+'[[%d]] -- '*5+"'''%d'''...
pre='(\r?\n)+' post='(\r?\n)+' R9=re.compile(pre+'\\<!-- robot --\\>.*\\<!-- /robot --\\>'+post)
pre='(\r?\n)+ *' post=' *(\r?\n)+' R9=re.compile(pre+'<!-- robot -->(.|\n)+?<!-- /robot -->'+post,re.MULTILINE)
def header(year): s=[] cent=(int(year)-1)/100+1 s.append('<!-- robot -->') s.append('<table align=center><tr><td align=center>') s.append("[[Eeuwen]]: [[%de eeuw]] -- '''[[%de eeuw]]''' -- [[%de eeuw]]"%tuple(range(cent-1,cent+2))) s.append('</td></tr><tr><td align=center>') s.append(('Jaren: '+'[[%d]] -- '*5+"'''%d'''...
orgtext=text
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) if R6.search(te...
if R6.search(text): m=R6.search(text).group(0) print "MATCH:", len(m),repr(m)
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) if R6.search(te...
print text
f=open('/tmp/wik.in','w') f.write(orgtext) f.close() f=open('/tmp/wik.out','w') f.write(text) f.close() f=os.popen('diff -u /tmp/wik.in /tmp/wik.out','r') print f.read()
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) if R6.search(te...
status,reason,data=wikipedia.putPage('test','Robottest',text)
status,reason,data=wikipedia.putPage(mylang,page,text)
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) if R6.search(te...
self.mysite = wikipedia.getSite() pl=wikipedia.PageLink(self.mysite,arg[5:])
mysite = wikipedia.getSite() pl=wikipedia.PageLink(mysite, arg[5:])
def main(): # the option that's always selected when the bot wonders what to do with # a link. If it's None, the user is prompted (default behaviour). always = None alternatives = [] getAlternatives = True solve_redirect = False # if the -file argument is used, page titles are dumped in this array. # otherwise it will ...
sys.stderr.write('AllPages: %d done; continuing from "%s";\n'%(m,url2link(start,code='nl',incode='ascii')))
def allpages(start = '%21%200'): """Iterate over all Wikipedia pages in the home language, starting at the given page.""" start = link2url(start, code = mylang) m=0 while 1: text = getPage(mylang, family.allpagesname(mylang, start), do_quote=0, do_edit=0) #print text if family.version(mylang)=="1.2": R = re.compile('/w...
return u'{| border="1"\n' + u'\n|----\n'.join(lines) + '\n|}'
return u'{| border="1"\n! date/time || username || resolution || size || edit summary\n|----\n| ' + u'\n|----\n'.join(lines) + '\n|}'
def getFileVersionHistoryTable(self): lines = [] for (datetime, username, resolution, size, comment) in self.getFileVersionHistory(): lines.append('%s || %s || %s || %s || <nowiki>%s</nowiki>' % (datetime, username, resolution, size, comment)) return u'{| border="1"\n' + u'\n|----\n'.join(lines) + '\n|}'
if first in site.family.langs or first in site.family.known_families:
if first in site.family.langs or (first in site.family.known_families and site.family.known_families[first] != site.family.name):
def isInterwikiLink(s, site = None): """ Try to check whether s is in the form "foo:bar" where foo is a known language code or family. In such a case we are dealing with an interwiki link. """ if not ':' in s: return False site = site or getSite() first, rest = s.split(':',1) # interwiki codes are case-insensitive firs...
Page(self, "%s:Sandbox" % self.family.namespace(self.lang, 4)).get(force = True, sysop = sysop)
Page(self, "%s:Sandbox" % self.family.namespace(self.lang, 4)).get(force = True, get_redirect = True, sysop = sysop)
def getToken(self, getalways = True, getagain = False, sysop = False): if getagain or (getalways and ((sysop and not self._sysoptoken) or (not sysop and not self._token))): output(u"Getting page to get a token.") try: Page(self, "%s:Sandbox" % self.family.namespace(self.lang, 4)).get(force = True, sysop = sysop) #Page(...
wikipedia.output("Skipping link %s to an ignored page"%page2)
wikipedia.output(u"Skipping link %s to an ignored page"%page2)
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 ...
output(u"WARNING: [[%s]] is a double-redirect.")
output(u"WARNING: [[%s]] is a double-redirect." % item.group(1))
def getReferences(self, follow_redirects=True, offset=0): """ Return a list of pages that link to the page. If follow_redirects is True, also returns pages that link to a redirect pointing to the page. If offset is non-zero, skips that many references before loading. """ site = self.site() path = site.references_addres...
output(u"ERROR> link from %s to %s:%s has leading colon?!" % (self.linkname(), newsite, newname))
output(u"ERROR: link from %s to [[%s:%s]] has leading colon?!" % (self.aslink(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s has leading space?!" % (self.linkname(), newsite, newname))
output(u"ERROR: link from %s to [[%s:%s]] has leading space?!" % (self.aslink(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
except UnicodeEncodeError: output(u"ERROR> link from %s to %s:%s is invalid encoding?!" % (self.linkname(), newsite, newname))
except UnicodeError: output(u"ERROR: link from %s to [[%s:%s]] is invalid encoding?!" % (self.aslink(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s contains invalid character?!" % (self.linkname(), newsite, newname))
output(u"ERROR: link from %s to [[%s:%s]] contains invalid character?!" % (self.aslink(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s contains invalid unicode reference?!" % (self.linkname(), newsite, newname))
output(u"ERROR: link from %s to [[%s:%s]] contains invalid unicode reference?!" % (self.aslink(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
pagenames = pagenames.encode(site.encoding())
pagenames = pagenames.encode(self.site.encoding())
def getData(self): if self.pages == []: return address = self.site.export_address() # In the next line, we assume that what we got for eo: is NOT in x-convention # but SHOULD be. This is worst-case; to avoid not getting what we need, if we # find nothing, we will retry the normal way with an unadapted form. pagenames =...
for encoding in ('utf-8',)+site.encodings():
for encoding in site.encodings():
def url2unicode(percentname, site): # Does the input string contain non-ascii characters? In that case, # it is not really an url, and we do not have to unquote it.... for c in percentname: if ord(c)>128: x=percentname break else: # Before removing the % encoding, make sure it is an ASCII string. # unquote doesn't work...
encode_func, decode_func, stream_reader, stream_writer = codecs.lookup(encoding) x,l = decode_func(x)
x = x.encode(encoding)
def url2unicode(percentname, site): # Does the input string contain non-ascii characters? In that case, # it is not really an url, and we do not have to unquote it.... for c in percentname: if ord(c)>128: x=percentname break else: # Before removing the % encoding, make sure it is an ASCII string. # unquote doesn't work...
except UnicodeError:
except:
def url2unicode(percentname, site): # Does the input string contain non-ascii characters? In that case, # it is not really an url, and we do not have to unquote it.... for c in percentname: if ord(c)>128: x=percentname break else: # Before removing the % encoding, make sure it is an ASCII string. # unquote doesn't work...
'minnan':'zh-min-nan.wiktionary.org', 'nb':'no.wiktionary.org', 'zh-cn':'zh.wiktionary.org', 'zh-tw':'zh.wiktionary.org'
'minnan':'zh-min-nan.wikibooks.org', 'nb':'no.wikibooks.org', 'zh-cn':'zh.wikibooks.org', 'zh-tw':'zh.wikibooks.org'
def __init__(self): family.Family.__init__(self) self.name = 'wikibooks' # Known wikibooks languages, given as a dictionary mapping the language code # to the hostname of the site hosting that wiktibooks. For human consumption, # the full name of the language is given behind each line as a comment self.langs = { 'minna...
self.langs[lang] = lang+'.wiktionary.org'
self.langs[lang] = '%s.wikibooks.org' % lang
def __init__(self): family.Family.__init__(self) self.name = 'wikibooks' # Known wikibooks languages, given as a dictionary mapping the language code # to the hostname of the site hosting that wiktibooks. For human consumption, # the full name of the language is given behind each line as a comment self.langs = { 'minna...
if wikipedia.config.disambiguation_comment[ self.mysite.family.name][self.mylang]:
if wikipedia.config.disambiguation_comment.has_key(self.mysite.family.name) and wikipedia.config.disambiguation_comment[self.mysite.family.name].has_key(self.mylang):
def run(self): if self.main_only: if not ignore_title.has_key(self.mysite.family.name): ignore_title[self.mysite.family.name] = {} if not ignore_title[self.mysite.family.name].has_key(self.mylang): ignore_title[self.mysite.family.name][self.mylang] = [] ignore_title[self.mysite.family.name][self.mylang] += [ u'%s:' % n...
self.subentries[self.wikilang] = subentry
self.subentries.setdefault(subentry.subentrylang, []).append(subentry)
def addSubEntry(self,subentry):
while 1:
while i< len(self.sortedsubentries):
def sortSubentries(self): print self.subentries if not self.subentries == {}: self.sortedsubentries = self.subentries.keys() self.sortedsubentries.sort(sortonname(langnames[self.wikilang])) print "should now be sorted: %s"%self.sortedsubentries i = 0 while 1: x = self.sortedsubentries[i] if x == self.wikilang: # sear...
for subentry in self.sortedsubentries: entry= entry + self.subentries[subentry].wikiwrap(self.wikilang) + '\n'
for index in self.sortedsubentries: for subentry in self.subentries[index]: entry= entry + subentry.wikiwrap(self.wikilang) + '\n----\n'
def wikiwrap(self): entry = '' self.sortSubentries() print "sorted: %s",self.sortedsubentries for subentry in self.sortedsubentries: entry= entry + self.subentries[subentry].wikiwrap(self.wikilang) + '\n'
self.subentries[subentrieskey].showcontents(indentation+2)
for subentry in self.subentries[subentrieskey]:
def showcontents(self): indentation = 0 print ' ' * indentation + 'wikilang = %s'% self.wikilang
subentry.showcontents(indentation+2)
def showcontents(self): indentation = 0 print ' ' * indentation + 'wikilang = %s'% self.wikilang
result = ''
result = u''
def removeEntity(name): import re, htmlentitydefs Rentity = re.compile(r'&([A-Za-z]+);') result = '' i = 0 while i < len(name): m = Rentity.match(name[i:]) if m: if htmlentitydefs.entitydefs.has_key(m.group(1)): result = result + htmlentitydefs.entitydefs[m.group(1)] i += m.end() else: result += name[i] i += 1 else: re...
if htmlentitydefs.entitydefs.has_key(m.group(1)): result = result + htmlentitydefs.entitydefs[m.group(1)]
if htmlentitydefs.name2codepoint.has_key(m.group(1)): x = htmlentitydefs.name2codepoint[m.group(1)] result = result + unichr(x)
def removeEntity(name): import re, htmlentitydefs Rentity = re.compile(r'&([A-Za-z]+);') result = '' i = 0 while i < len(name): m = Rentity.match(name[i:]) if m: if htmlentitydefs.entitydefs.has_key(m.group(1)): result = result + htmlentitydefs.entitydefs[m.group(1)] i += m.end() else: result += name[i] i += 1 else: re...
name = unicodeName(name, language, altlanguage)
def html2unicode(name, language, altlanguage=None): name = removeEntity(name) name = unicodeName(name, language, altlanguage) import re Runi = re.compile('&#(\d+);') result = u'' i=0 while i < len(name): m = Runi.match(name[i:]) if m: result += unichr(int(m.group(1))) i += m.end() else: try: result += name[i] i += 1 e...
choice = wikipedia.input(u'Do you want to work on pages linking to %s?' % refpl.linkname(), ['yes', 'no', 'change redirect'], ['y', 'N', 'c'], 'N')
choice = wikipedia.inputChoice(u'Do you want to work on pages linking to %s?' % refpl.linkname(), ['yes', 'no', 'change redirect'], ['y', 'N', 'c'], 'N')
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. """
pre='((\r?\n)*---- *)?(\r?\n)?(\'\'\')?'
pre='((\r?\n)*---- *)?(\r?\n)*(\'\'\')?'
def header(year): s=[] cent=(int(year)-1)/100+1 s.append('<!-- robot -->') s.append('<table align=center><tr><td align=center>') s.append("[[Eeuwen]]: [[%s]] -- '''[[%s]]''' -- [[%s]]"%cmap(beforeandafter(cent))) s.append('</td></tr><tr><td align=center>') s.append(('Jaren: '+'[[%s]] -- '*5+"'''%s'''"+' -- [[%s]]'*5)%y...
R2=re.compile(pre+'(Overleden|Sterfdata|Gestorven)'+post,re.MULTILINE)
R2=re.compile(pre+'(Overleden|Sterf(te)?data|Gestorven)'+post,re.MULTILINE)
def header(year): s=[] cent=(int(year)-1)/100+1 s.append('<!-- robot -->') s.append('<table align=center><tr><td align=center>') s.append("[[Eeuwen]]: [[%s]] -- '''[[%s]]''' -- [[%s]]"%cmap(beforeandafter(cent))) s.append('</td></tr><tr><td align=center>') s.append(('Jaren: '+'[[%s]] -- '*5+"'''%s'''"+' -- [[%s]]'*5)%y...
pre='((\r?\n)+---- *)?(\r?\n)'
pre='((\r?\n)+---- *)?(\r?\n)+'
def header(year): s=[] cent=(int(year)-1)/100+1 s.append('<!-- robot -->') s.append('<table align=center><tr><td align=center>') s.append("[[Eeuwen]]: [[%s]] -- '''[[%s]]''' -- [[%s]]"%cmap(beforeandafter(cent))) s.append('</td></tr><tr><td align=center>') s.append(('Jaren: '+'[[%s]] -- '*5+"'''%s'''"+' -- [[%s]]'*5)%y...
R8=re.compile(pre+'\[\[[Ee]euwen\]\]:? *[-\\[\\]\\<\\>\'\| 0-9euwvChr\.]{14,70}'+post,re.MULTILINE)
R8=re.compile(pre+'\[\[[Ee]euwen\]\]:? *(\\<\\/?b\\>|eeuw|[-\\[\\]\\<\\>\'\| 0-9evChr\.]){14,70}'+post,re.MULTILINE)
def header(year): s=[] cent=(int(year)-1)/100+1 s.append('<!-- robot -->') s.append('<table align=center><tr><td align=center>') s.append("[[Eeuwen]]: [[%s]] -- '''[[%s]]''' -- [[%s]]"%cmap(beforeandafter(cent))) s.append('</td></tr><tr><td align=center>') s.append(('Jaren: '+'[[%s]] -- '*5+"'''%s'''"+' -- [[%s]]'*5)%y...
text=wikipedia.getPage(mylang,page)
try: text=wikipedia.getPage(mylang,page) except wikipedia.NoPage: return
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) orgtext=text # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) te...
f=open('/tmp/wik.in','w') f.write(orgtext) f.close() f=open('/tmp/wik.out','w') f.write(text) f.close() f=os.popen('diff -u /tmp/wik.in /tmp/wik.out','r') print f.read()
if 0: f=open('/tmp/wik.in','w') f.write(orgtext) f.close() f=open('/tmp/wik.out','w') f.write(text) f.close() f=os.popen('diff -u /tmp/wik.in /tmp/wik.out','r') print f.read() else: print text
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) orgtext=text # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) te...