rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
print "WARNING: Link to unknown language %s" % (match.group(1))
print "WARNING: Link to unknown language %s" % (interwikiMatch.group(1))
def removeLanguageLinks(text, site = None): """Given the wiki-text of a page, return that page with all interwiki links removed. If a link to an unknown language is encountered, a warning is printed.""" if site == None: site = getSite() # This regular expression will find every link that is possibly an # interwiki link...
print "OK. I'm not uploading"
def convert(text): ''' Converts all HTML tables in text to wiki syntax. If text contains wiki tables, tries to beautify them. Returns converted text if page was successfully changed, otherwise returns None. ''' warnings = 0 # this array will contain strings that will be shown in case of possible # errors, before the us...
print "No changes were necessary in " + article
print "No changes were necessary"
def convert(text): ''' Converts all HTML tables in text to wiki syntax. If text contains wiki tables, tries to beautify them. Returns converted text if page was successfully changed, otherwise returns None. ''' warnings = 0 # this array will contain strings that will be shown in case of possible # errors, before the us...
self.langs[lang] = lang+'.wikipedia.org'
if lang not in self.langs: self.langs[lang] = lang+'.wikipedia.org'
def __init__(self): family.Family.__init__(self) self.name = 'wikipedia'
pass try: thistxt = removeCategoryLinks(self.get(), self.code()) except IsRedirectPage: pass
return thistxt = removeCategoryLinks(thistxt, self.code())
def links(self): # Gives the normal (not-interwiki, non-category) pages the page # directs to, as strings result = [] try: thistxt = removeLanguageLinks(self.get()) except IsRedirectPage: pass try: thistxt = removeCategoryLinks(self.get(), self.code()) except IsRedirectPage: pass w=r'([^\]\|]*)' Rlink = re.compile(r'\[...
return getPage(self.code(),self.urlname())
if not hasattr(self,'_contents'): self._contents=getPage(self.code(),self.urlname()) return self._contents
def get(self): return getPage(self.code(),self.urlname())
('wpEdittime', edittime[code,space2underline(name)]),
('wpEdittime', edittime[code,link2url(name,code)]),
def putPage(code, name, text, comment=None): """Upload 'text' on page 'name' to the 'code' language wikipedia.""" import httplib host = langs[code] if host[-4:] == '.com': raise Error("Cannot put pages on a .com wikipedia") address = '/w/wiki.phtml?title=%s&action=submit'%space2underline(name) if comment is None: comme...
uo=urllib.FancyURLopener()
uo=MyURLopener()
def getUrl(host,address): uo=urllib.FancyURLopener() f=uo.open('http://%s%s'%(host,address)) text=f.read() ct=f.info()['Content-Type'] R=re.compile('charset=([^\'\"]+)') m=R.search(ct) if m: charset=m.group(1) else: charset=None return text,charset
edittime[code,space2underline(name)]=m.group(1)
edittime[code,link2url(name,code)]=m.group(1)
def getPage(code, name, do_edit=1, do_quote=1): """Get the contents of page 'name' from the 'code' language wikipedia""" host = langs[code] if host[-4:]=='.com': # Old algorithm name = re.sub('_', ' ', name) n=[] for x in name.split(): n.append(x[0].capitalize()+x[1:]) name='_'.join(n) #print name else: name = re.sub('...
edittime[code,name]=m.group(1)
edittime[code,link2url(name,code)]=m.group(1)
def getPage(code, name, do_edit=1, do_quote=1): """Get the contents of page 'name' from the 'code' language wikipedia""" host = langs[code] if host[-4:]=='.com': # Old algorithm name = re.sub('_', ' ', name) n=[] for x in name.split(): n.append(x[0].capitalize()+x[1:]) name='_'.join(n) #print name else: name = re.sub('...
edittime[code,name]=0
edittime[code,link2url(name,code)]=0
def getPage(code, name, do_edit=1, do_quote=1): """Get the contents of page 'name' from the 'code' language wikipedia""" host = langs[code] if host[-4:]=='.com': # Old algorithm name = re.sub('_', ' ', name) n=[] for x in name.split(): n.append(x[0].capitalize()+x[1:]) name='_'.join(n) #print name else: name = re.sub('...
description = raw_input('Description : ')
description = description.encode('utf-8') if description=='': description = raw_input('Description : ')
def get_image(fn,target,description): # 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] print "The filename on wikipedia will default to:",fn newfn = raw_input("Bette...
pls.append(pl) i += 1 if i >= 60: self.start = pl.urlname() + '!' break wikipedia.getall(wikipedia.getSite(), pls) for pl in pls: if not pl.isRedirectPage(): yield pl.linkname(), pl.get()
pls.append(pl) i += 1 if i >= 60: wikipedia.getall(wikipedia.getSite(), pls) for pl in pls: if not pl.isRedirectPage(): yield pl.linkname(), pl.get() i = 0 pls = []
def generate(self): while True: i = 0 pls = [] for pl in wikipedia.allpages(start = self.start): pls.append(pl) i += 1 if i >= 60: self.start = pl.urlname() + '!' break wikipedia.getall(wikipedia.getSite(), pls) for pl in pls: if not pl.isRedirectPage(): yield pl.linkname(), pl.get()
acceptall = True
self.acceptall = True
def run(self): """ Starts the robot. """ # Run the generator which will yield PageLinks to pages which might need to be # changed. for pl in self.generator(): print '' try: # Load the page's text from the wiki original_text = pl.get() except wikipedia.NoPage: wikipedia.output(u'Page %s not found' % pl.linkname()) conti...
newTable = re.sub("(CAPTION|caption)([\w\W]*?)<\/caption>",
newTable = re.sub("<(CAPTION|caption)([\w\W]*?)<\/caption>",
def convertTable(self, table): ''' Converts an HTML table to wiki syntax. If the table already is a wiki table or contains a nested wiki table, tries to beautify it. Returns the converted table, the number of warnings that occured and a list containing these warnings.
fix = fixes[fix]
try: fix = fixes[fix] except KeyError: wikipedia.output(u'Available predefined fixes are: %s' % fixes.keys()) sys.exit()
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 ...
yearBCfmt = {'da':'%d f.Kr.', 'de':'%d v. Chr.', 'en':'%d BC', 'fr':'-%d', 'pl':'%d p.n.e.', 'es':'%d adC', 'eo':'-%d', 'nl':'%d v. Chr.'}
yearBCfmt = { 'da':'%d f.Kr.', 'de':'%d v. Chr.', 'en':'%d BC', 'fr':'-%d', 'pl':'%d p.n.e.', 'es':'%d adC', 'eo':'-%d', 'nl':'%d v. Chr.', 'is':'%d f. Kr.' }
def __call__(self, m, d): import wikipedia return wikipedia.html2unicode((date_format[m][self.code]) % d, language = self.code)
datetable = {'nl': { 'januari':{ 'sl':'%d. januar', 'it':'%d gennaio', 'en':'January %d', 'de':'%d. Januar', 'fr':'%d janvier', 'af':'01-%02d', 'ca':'%d de gener', 'oc':'%d de geni%%C3%%A8r', }, 'februari':{ 'sl':'%d. februar', 'it':'%d febbraio', 'en':'February %d', 'de':'%d. Februar', 'fr':'...
datetable = { 'nl':{ 'januari':{ 'sl':'%d. januar', 'it':'%d gennaio', 'en':'January %d', 'de':'%d. Januar', 'fr':'%d janvier', 'af':'01-%02d', 'ca':'%d de gener', 'oc':'%d de geni%%C3%%A8r', 'is':'%d. janúar', }, 'februari':{ 'sl':'%d. februar', 'it':'%d febbraio', 'en':'February %d', 'de':'%d. Februar', 'fr':'%d fevr...
def __call__(self, m, d): import wikipedia return wikipedia.html2unicode((date_format[m][self.code]) % d, language = self.code)
isoDate = time.strftime('%Y-%m-%d %H:%M:%S', date)
isoDate = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(date))
def log(self, url, error, containingPage): """ Logs an error report to a text file in the deadlinks subdirectory. """ site = wikipedia.getSite() errorReport = u'* %s\n' % url for (pageTitle, date, error) in self.historyDict[url]: # ISO 8601 formulation isoDate = time.strftime('%Y-%m-%d %H:%M:%S', date) errorReport += "...
elif pl.linkname().lower() == pl.linkname():
elif pl.linkname()[0].upper() == pl.linkname()[0]:
def sametranslate(pl, arr, same): site = pl.site() for newcode in site.family.seriouslangs: # Put as suggestion into array newname = pl.linkname() if newcode in ['eo','cs'] and same == 'name': newname = newname.split(' ') newname[-1] = newname[-1].upper() newname = ' '.join(newname) x=wikipedia.PageLink(wikipedia.getSi...
start = None
start = u'!'
def main(): start = None 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 start: gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle = ' '.join(pageTitle) page = wikipedia.Page(wi...
if start:
if pageTitle == []:
def main(): start = None 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 start: gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle = ' '.join(pageTitle) page = wikipedia.Page(wi...
wikipedia.output(u"* %s" % pl.aslink())
wikipedia.output(u"* %s" % curpl.aslink())
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' print "This bot has two modes: you can add a category link to all" print "pages mentioned in a List that is now in another wikipedia page" print "or you can add a category link to all pages that link to a" print "spe...
cats.append(catpl)
rawcats.append(catpl)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' print "This bot has two modes: you can add a category link to all" print "pages mentioned in a List that is now in another wikipedia page" print "or you can add a category link to all pages that link to a" print "spe...
text = wikipedia.replaceCategoryLinks(text, cats)
text = wikipedia.replaceCategoryLinks(text, rawcats)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' print "This bot has two modes: you can add a category link to all" print "pages mentioned in a List that is now in another wikipedia page" print "or you can add a category link to all pages that link to a" print "spe...
newURL = None
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. ''' # TODO: Malconfigured HTTP servers might give a redirect loop. A # recursion counter and limit would help. conn = httplib.HTTPConnection(self.host...
if redirTarget.startswith('http://') or redirTarget.startswith('https://'): newURL = redirTarget elif redirTarget.startswith('/'): newURL = '%s://%s%s' % (self.protocol, self.host, redirTarget) else: newURL = '%s://%s/%s' % (self.protocol, self.host, redirTarget)
if redirTarget: if redirTarget.startswith('http://') or redirTarget.startswith('https://'): newURL = redirTarget elif redirTarget.startswith('/'): newURL = '%s://%s%s' % (self.protocol, self.host, redirTarget) else: 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. ''' # TODO: Malconfigured HTTP servers might give a redirect loop. A # recursion counter and limit would help. conn = httplib.HTTPConnection(self.host...
result = {}
result = []
def translate(page, hints = None, auto = True): """ Please comment your source code! --Daniel Does some magic stuff. Returns a list of pages. """ result = {} site = page.site() if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, n...
newtext = replaceLanguageLinks(newtext, interwiki_links)
newtext = replaceLanguageLinks(newtext, interwiki_links, site = site)
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() # first remove interwiki links and add them later, so that # interwiki tags appear b...
if not disambPage.isRedirectPage(): disambigText = editor.edit(disambPage.get(), jumpIndex = m.start())
if disambPage.isRedirectPage(): disambredir1 = disambPage.getRedirectTarget() disambredir2 = wikipedia.Page(wikipedia.getSite(), disambredir1) disambigText = editor.edit(disambredir2.get(), jumpIndex = m.start(), highlight = disambredir2.title()) else: disambigText = editor.edit(disambPage.get(), jumpIndex = m.start(),...
def treat(self, refPage, disambPage): """ Parameters: disambPage - The disambiguation page or redirect we don't want anything to link on refPage - A page linking to disambPage Returns False if the user pressed q to completely quit the program. Otherwise, returns True. """ # TODO: break this function up into subroutines...
dictionary = cache[site]
watchlist = cache[site]
def get(site = None): if site is None: site = wikipedia.getSite() if cache.has_key(site): # Use cached copy if it exists. dictionary = cache[site] else: fn = 'watchlists/watchlist-%s-%s.dat' % (site.family.name, site.lang) try: # find out how old our saved dump is (in seconds) file_age = time.time() - os.path.getmtime(...
wikipedia.output(u"Current categories: ", cats)
wikipedia.output(u"Current categories: %s" % cats)
def add_category(sort_by_last_name = False): ''' A robot to mass-add a category to a list of pages. ''' print "This bot has two modes: you can add a category link to all" print "pages mentioned in a List that is now in another wikipedia page" print "or you can add a category link to all pages that link to a" print "spe...
Rredir = re.compile('\<li\>\<a href=\"\/w\/wiki.phtml\?title=(.*?)&amp;redirect=no\"')
Rredir = re.compile('\<li\>\<a href=".+?" title="(.*?)"')
def retrieve_broken_redirects(self): if self.source == None: # retrieve information from the live wiki's maintenance page mysite = wikipedia.getSite() # broken redirect maintenance page's URL path = mysite.broken_redirects_address(default_limit = False) print 'Retrieving special page...' maintenance_txt = wikipedia.get...
for hit in R.findall(text):
for hit in R.findall(tet):
def allpages(start = '%21%200'): """Iterate over all Wikipedia pages in the home language, starting at the given page. This will raise an exception if the home language does not have a translation of 'Special' listed above.""" import sys start = link2url(start, code = mylang) m=0 while 1: text = getPage(mylang, '%s:All...
Rref = re.compile('<li><a href.* title="([^"]*)"')
Rref = re.compile('<li><a href.*="([^"]*)"')
def getReferences(pl): host = langs[pl.code()] url = "/w/wiki.phtml?title=%s:Whatlinkshere&target=%s"%(special[mylang], pl.urlname()) txt, charset = getUrl(host,url) Rref = re.compile('<li><a href.* title="([^"]*)"') x = Rref.findall(txt) x.sort() # Remove duplicates for i in range(len(x)-1, 0, -1): if x[i] == x[i-1]: ...
self.problem("Found link to %s" % pl.aslink() )
self.problem("Found link to %s" % pl.aslink(forceInterwiki = True) )
def assemble(self): # No errors have been seen so far nerr = 0 # Build up a dictionary of all links found, with the site as key. # Each value will be a list. mysite = wikipedia.getSite() new = {} for pl in self.done.keys(): site = pl.site() if site == mysite and pl.exists() and not pl.isRedirectPage(): if pl != self.i...
for pl2 in v:
for page2 in v:
def assemble(self): # No errors have been seen so far nerr = 0 # Build up a dictionary of all links found, with the site as key. # Each value will be a list. mysite = wikipedia.getSite() new = {} for pl in self.done.keys(): site = pl.site() if site == mysite and pl.exists() and not pl.isRedirectPage(): if pl != self.i...
wikipedia.output(u" (%d) Found link to %s in:" % (i, pl2.aslink())) self.whereReport(pl2, indent=8)
wikipedia.output(u" (%d) Found link to %s in:" % (i, page2.aslink(forceInterwiki = True))) self.whereReport(page2, indent=8)
def assemble(self): # No errors have been seen so far nerr = 0 # Build up a dictionary of all links found, with the site as key. # Each value will be a list. mysite = wikipedia.getSite() new = {} for pl in self.done.keys(): site = pl.site() if site == mysite and pl.exists() and not pl.isRedirectPage(): if pl != self.i...
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.
self.replaceLinks(page, new, sa)
if self.replaceLinks(page, new, sa): updatedSites.append(site) for site in updatedSites: del new[site]
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.
try: wikipedia.showDiff(oldtext, newtext) except: wikipedia.output(u'Error executing showDiff')
wikipedia.showDiff(oldtext, newtext)
def replaceLinks(self, pl, new, sa): wikipedia.output(u"Updating links on page %s." % pl.aslink(forceInterwiki = True))
if globalvar.forreal:
ask = False if removing: self.problem('removing: %s'%(",".join([x.lang for x in removing]))) ask = True if globalvar.force:
def replaceLinks(self, pl, new, sa): wikipedia.output(u"Updating links on page %s." % pl.aslink(forceInterwiki = True))
if removing: self.problem('removing: %s'%(",".join([x.lang for x in removing]))) ask = True if globalvar.force: ask = False if globalvar.confirm: ask = True if ask: if globalvar.autonomous: answer = 'n'
if globalvar.confirm: ask = True if ask: if globalvar.autonomous: answer = 'n' else: answer = wikipedia.inputChoice(u'Submit?', ['Yes', 'No'], ['y', 'N'], 'N') else: answer = 'y' if answer == 'y': if sa: while wikipedia.get_throttle.waittime() + 2.0 < wikipedia.put_throttle.waittime(): print "NOTE: Performing a r...
def replaceLinks(self, pl, new, sa): wikipedia.output(u"Updating links on page %s." % pl.aslink(forceInterwiki = True))
answer = wikipedia.inputChoice(u'Submit?', ['Yes', 'No'], ['y', 'N'], 'N')
break if str(status) == '302': return True
def replaceLinks(self, pl, new, sa): wikipedia.output(u"Updating links on page %s." % pl.aslink(forceInterwiki = True))
answer = 'y' if answer == 'y': if sa: while wikipedia.get_throttle.waittime() + 2.0 < wikipedia.put_throttle.waittime(): print "NOTE: Performing a recursive query first to save time...." qdone = sa.oneQuery() if not qdone: break print "NOTE: Updating live wiki..." timeout=60 while 1: try: print "DBG> updating ", ...
print status, reason return False
def replaceLinks(self, pl, new, sa): wikipedia.output(u"Updating links on page %s." % pl.aslink(forceInterwiki = True))
for site in new.keys(): pl = new[site] if not pl.section():
for site, page in new.iteritems(): if not page.section():
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked:
linked = page.interwiki() for xpage in shouldlink: if xpage != page and not xpage in linked:
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
if l.site() == xpl.site(): wikipedia.output(u"WARNING: %s: %s does not link to %s but to %s" % (pl.site().family.name, pl.aslink(forceInterwiki = True), xpl.aslink(forceInterwiki = True), l.aslink(forceInterwiki = True)))
if l.site() == xpage.site(): wikipedia.output(u"WARNING: %s: %s does not link to %s but to %s" % (page.site().family.name, page.aslink(forceInterwiki = True), xpage.aslink(forceInterwiki = True), l.aslink(forceInterwiki = True)))
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
wikipedia.output(u"WARNING: %s: %s does not link to %s" % (pl.site().family.name, pl.aslink(forceInterwiki = True), xpl.aslink(forceInterwiki = True)))
wikipedia.output(u"WARNING: %s: %s does not link to %s" % (page.site().family.name, page.aslink(forceInterwiki = True), xpage.aslink(forceInterwiki = True)))
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
for xpl in linked: if not xpl in shouldlink:
for xpage in linked: if not xpage in shouldlink:
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
if l.site() == xpl.site():
if l.site() == xpage.site():
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
wikipedia.output(u"WARNING: %s: %s links to incorrect %s" % (pl.site().family.name, pl.aslink(forceInterwiki = True), xpl.aslink(forceInterwiki = True)))
wikipedia.output(u"WARNING: %s: %s links to incorrect %s" % (page.site().family.name, page.aslink(forceInterwiki = True), xpage.aslink(forceInterwiki = True)))
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" try: for site in new.keys(): pl = new[site] if not pl.section(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in linked: if l....
print pl.site().hostname() print pl.site().delete_address(pl.urlname())
def encode_multipart_formdata(fields): """ 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 (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$' CRLF =...
print arg
def main(args): filename = '' description = [] keep = False wiki = '' for arg in args: if wikipedia.argHandler(arg, 'upload'): print arg if arg.startswith('-keep'): keep = True elif arg.startswith('-wiki:'): wiki=arg[6:] elif filename == '': filename = arg else: description.append(arg) description = ' '.join(descripti...
except IsRedirectPage:
except wikipedia.IsRedirectPage:
def handlebadpage(self): try: self.content = self.page.get() except IsRedirectPage: wikipedia.output(u'Already redirected, skipping.') return
wikipedia.output(u'Found: "',d, '" in content, nothing necessary')
wikipedia.output(u'Found: "%s" in content, nothing necessary'%d)
def handlebadpage(self): try: self.content = self.page.get() except IsRedirectPage: wikipedia.output(u'Already redirected, skipping.') return
output(url2unicode("Creating page [[%s:%s]]" % site.lang, name, site = site))
output(url2unicode("Creating page [[%s:%s]]" % (site.lang, name), site = site))
def putPage(site, name, text, comment = None, watchArticle = False, minorEdit = True, newPage = False, token = None, gettoken = False): """Upload 'text' on page 'name' to the 'site' wiki. Use of this routine can normally be avoided; use Page.put instead. """ safetuple = () # safetuple keeps the old value, but only if w...
output(url2unicode("Changing page [[%s:%s]]" % site.lang, name, site = site))
output(url2unicode("Changing page [[%s:%s]]" % (site.lang, name), site = site))
def putPage(site, name, text, comment = None, watchArticle = False, minorEdit = True, newPage = False, token = None, gettoken = False): """Upload 'text' on page 'name' to the 'site' wiki. Use of this routine can normally be avoided; use Page.put instead. """ safetuple = () # safetuple keeps the old value, but only if w...
output(url2unicode(u'Getting page [[%s:%s]]' % site.lang, name, site = site))
output(url2unicode(u'Getting page [[%s:%s]]' % (site.lang, name), site = site))
def getEditPage(site, name, 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 Page object instead. Arguments: site - the wiki site name - the page n...
wikipedia.getall(wikipedia.getSite(), pages, throttle=False)
site = pages[0].site() wikipedia.getall(site, pages, throttle=False) except IndexError: pass
def preload(self, pages): try: wikipedia.getall(wikipedia.getSite(), pages, throttle=False) except wikipedia.SaxError: # Ignore this error, and get the pages the traditional way later. pass
output("WARNING: Section does not exist: %s" % self.linkname())
output(u"WARNING: Section does not exist: %s" % self.linkname())
def get(self, read_only = False, force = False, get_redirect=False, throttle = True): """The wiki-text of the page. This will retrieve the page if it has not been retrieved yet. This can raise the following exceptions that should be caught by the calling code:
output("WARNING: Section does not exist: %s" % self)
output(u"WARNING: Section does not exist: %s" %pl2.linkname())
def oneDone(self, title, timestamp, text): pl = Page(self.site, title) for pl2 in self.pages: if Page(self.site, pl2.sectionFreeLinkname()) == pl: if not hasattr(pl2,'_contents') and not hasattr(pl2,'_getexception'): break else: print repr(title) print repr(pl) print repr(self.pages) print "BUG> bug, page not found in ...
txt = "
txt = redir.get(get_redirect=True).replace('[['+target,'[['+second_target)
def fix_double_redirects(self): mysite = wikipedia.getSite() for redir_name in self.generator.retrieve_double_redirects(): print '' redir = wikipedia.Page(mysite, redir_name) try: target = redir.getRedirectTarget() except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir.title()) except wik...
wikipedia.link2url(start)
start=link2url(start)
def allnlpages(start='%20%200'): wikipedia.link2url(start) m=0 while 1: text=wikipedia.getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0) #print text R=re.compile('/wiki/(.*?)" *class=[\'\"]printable') n=0 for hit in R.findall(text): if not ':' in hit: if not hit in ['Hoofdpagina','In_he...
text=wikipedia.getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0)
text=getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0)
def allnlpages(start='%20%200'): wikipedia.link2url(start) m=0 while 1: text=wikipedia.getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0) #print text R=re.compile('/wiki/(.*?)" *class=[\'\"]printable') n=0 for hit in R.findall(text): if not ':' in hit: if not hit in ['Hoofdpagina','In_he...
yield wikipedia.url2link(hit)
yield url2link(hit)
def allnlpages(start='%20%200'): wikipedia.link2url(start) m=0 while 1: text=wikipedia.getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0) #print text R=re.compile('/wiki/(.*?)" *class=[\'\"]printable') n=0 for hit in R.findall(text): if not ':' in hit: if not hit in ['Hoofdpagina','In_he...
sys.stderr.write('AllNLPages: %d done; continuing from "%s";\n'%(m,wikipedia.link2url(start)))
sys.stderr.write('AllNLPages: %d done; continuing from "%s";\n'%(m,url2link(start)))
def allnlpages(start='%20%200'): wikipedia.link2url(start) m=0 while 1: text=wikipedia.getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0) #print text R=re.compile('/wiki/(.*?)" *class=[\'\"]printable') n=0 for hit in R.findall(text): if not ':' in hit: if not hit in ['Hoofdpagina','In_he...
result[code] = m.group(1)
t=m.group(1) if '|' in t: t.replace('|','') result[code] = t
def getLanguageLinks(text): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}""" result = {} for code in langs: m=re.search(r'\[\['+code+':([^\]]*)\]\]', text) if m: if m.group(1): result[code] = m.group(1) else: print "ERROR: empty link to %s:"%(code) return result
elif arg.startswith('-page:'):
elif arg.startswith('-page'):
def main(): template_names = [] resolve = False remove = False namespaces = [] editSummary = '' acceptAll = False pageTitles = [] extras = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in wikipedia.handleArgs(): if arg ...
m = re.search('value="(\d+)" name=["\']wpEdittime["\']', text) if m: self._editTime = m.group(1) else: self._editTime = "0" m = re.search('value="(\d+)" name=["\']wpStarttime["\']', text) if m: self._startTime = m.group(1) else: self._startTime = "0"
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...
m = re.search('value="(\d+)" name=["\']wpEdittime["\']', text) if m: self._editTime = m.group(1) else: self._editTime = "0" m = re.search('value="(\d+)" name=["\']wpStarttime["\']', text) if m: self._startTime = m.group(1) else: self._startTime = "0"
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...
def isTalkPage(self): ns = self.namespace() return ns >= 0 and ns % 2 == 1
def isEmpty(self): """ True if the page has less than 4 characters, except for language links and category links, False otherwise. Can raise the same exceptions as get() """ txt = self.get() txt = removeLanguageLinks(txt) txt = removeCategoryLinks(txt, site = self.site()) if len(txt) < 4: return True else: return False
R=re.compile(r'\[\[(.*)]\]')
R=re.compile(r'\[\[(.+?)\]\]')
def PagesFromFile(fn, site = None): """Read a file of page links between double-square-brackets, and return them as a list of Page objects. 'fn' is the name of the file that should be read.""" if site is None: site = getSite() f=open(fn, 'r') R=re.compile(r'\[\[(.*)]\]') for line in f.readlines(): m=R.match(line) if m:...
except ValueError:
except:
def PagesFromFile(fn, site = None): """Read a file of page links between double-square-brackets, and return them as a list of Page objects. 'fn' is the name of the file that should be read.""" if site is None: site = getSite() f=open(fn, 'r') R=re.compile(r'\[\[(.*)]\]') for line in f.readlines(): m=R.match(line) if m:...
if summary == None:
if summary_commandline == None:
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 # summary message summary_commandline = None # Array which will collect commandline parameters. # First element is original text, second element is replacem...
Rnowiki = re.compile("<nowiki>*?</nowiki>")
Rnowiki = re.compile("<nowiki>.*?</nowiki>")
def linkedPages(self): """Gives the normal (not-interwiki, non-category) pages the page links to, as a list of Page objects """ result = [] try: thistxt = removeLanguageLinks(self.get()) except NoPage: return [] except IsRedirectPage: raise thistxt = removeCategoryLinks(thistxt, self.site())
e = code2encoding(incode) if e == 'utf-8':
return unicode2html(x, encoding = code2encoding(incode))
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) e = code2encoding(incode) if e == 'utf-8': # utf-8 can h...
return x elif e == code2encoding(code): return unicode2html(x, encoding = code2encoding(code)) else: return unicode2html(x, encoding = 'ascii')
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) e = code2encoding(incode) if e == 'utf-8': # utf-8 can h...
if hasattr(self, '_redirarg'): if not get_redirect: raise IsRedirectPage,self._redirarg elif hasattr(self, '_getexception'):
if hasattr(self, '_getexception'):
def get(self, read_only = False, force = False, get_redirect=False, throttle = True): """The wiki-text of the page. This will retrieve the page if it has not been retrieved yet. This can raise the following exceptions that should be caught by the calling code:
except LockedPage: self._getexception = LockedPage raise
def get(self, read_only = False, force = False, get_redirect=False, throttle = True): """The wiki-text of the page. This will retrieve the page if it has not been retrieved yet. This can raise the following exceptions that should be caught by the calling code:
self.get(read_only = True)
self.get(read_only = read_only)
def getRedirectTarget(self, read_only = False): """ If the page is a redirect page, gives the title of the page it redirects to. Otherwise it will raise an IsNotRedirectPage exception. This function can raise a NoPage exception, and unless the argument read_only is True, a LockedPage exception as well. """ try: self.g...
if edittime[site, name] == "0" and not read_only: output(u"DBG> page may be locked?!") raise LockedPage()
def getEditPage(site, name, read_only = False, 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 Page object instead. Arguments: site - the wiki site name - the page name read_only ...
import mediawiki_messages for i in pages_for_exclusion_database: path = 'copyright/' + i[0] + '/' + i[2] mediawiki_messages.makepath(path) p = wikipedia.Page(wikipedia.getSite(i[0]),i[1]) yield p, path
for i in pages_for_exclusion_database: path = 'copyright/' + i[0] + '/' + i[2] mediawiki_messages.makepath(path) p = wikipedia.Page(wikipedia.getSite(i[0]),i[1]) yield p, path
def exclusion_file_list(): import mediawiki_messages for i in pages_for_exclusion_database: path = 'copyright/' + i[0] + '/' + i[2] mediawiki_messages.makepath(path) p = wikipedia.Page(wikipedia.getSite(i[0]),i[1]) yield p, path
import time, os write = False for page, path in exclusion_file_list(): try: file_age = time.time() - os.path.getmtime(path) if file_age > 24 * 60 * 60: print 'Updating source pages to exclude new URLs...' write = True except OSError: write = True if write: f = codecs.open(path, 'w', 'utf-8') f.write(page.get()) f.clos...
write = False for page, path in exclusion_file_list(): try: file_age = time.time() - os.path.getmtime(path) if file_age > 24 * 60 * 60: print 'Updating source pages to exclude new URLs...' write = True except OSError: write = True if write: f = codecs.open(path, 'w', 'utf-8') f.write(page.get()) f.close() return
def load_pages(): import time, os write = False for page, path in exclusion_file_list(): try: file_age = time.time() - os.path.getmtime(path) if file_age > 24 * 60 * 60: print 'Updating source pages to exclude new URLs...' write = True except OSError: write = True if write: f = codecs.open(path, 'w', 'utf-8') f.write(...
import glob prelist = [] load_pages() for page, path in exclusion_file_list(): f = codecs.open(path, "r", 'utf-8') data = f.read() f.close() prelist += re.findall("(?i)url\s*=\s*<nowiki>(?:http://)?(.*?)</nowiki>", data) prelist += re.findall("(?i)\*\s*Site:\s*\[?(?:http://)?(.*?)\]?", data) if 'copyright/it/Cloni.tx...
prelist = [] load_pages() for page, path in exclusion_file_list(): f = codecs.open(path, "r", 'utf-8') data = f.read() f.close() prelist += re.findall("(?i)url\s*=\s*<nowiki>(?:http://)?(.*?)</nowiki>", data) prelist += re.findall("(?i)\*\s*Site:\s*\[?(?:http://)?(.*?)\]?", data) if 'copyright/it/Cloni.txt' in path: ...
def exclusion_list(): import glob prelist = [] load_pages() for page, path in exclusion_file_list(): f = codecs.open(path, "r", 'utf-8') data = f.read() f.close() # wikipedia:en:Wikipedia:Mirrors and forks prelist += re.findall("(?i)url\s*=\s*<nowiki>(?:http://)?(.*?)</nowiki>", data) prelist += re.findall("(?i)\*\s*Si...
text = re.sub("(?i){{quote|.*?}}", "", text) text = re.sub("^:''.*?''\.?\s*((\(|<ref>).*?(\)|</ref>))?\.?$", "", text) text = re.sub('^[:*]?["][^"]+["]\.?\s*((\(|<ref>).*?(\)|</ref>))?\.?$', "", text) text = re.sub('^[:*]?[«][^»]+[»]\.?\s*((\(|<ref>).*?(\)|</ref>))?\.?$', "", text) text = re.sub('^[:*]?[“][^”]+[”]\.?\s...
text = re.sub("(?i){{quote|.*?}}", "", text) text = re.sub("^:''.*?''\.?\s*((\(|<ref>).*?(\)|</ref>))?\.?$", "", text) text = re.sub('^[:*]?["][^"]+["]\.?\s*((\(|<ref>).*?(\)|</ref>))?\.?$', "", text) text = re.sub('^[:*]?[«][^»]+[»]\.?\s*((\(|<ref>).*?(\)|</ref>))?\.?$', "", text) text = re.sub('^[:*]?[“][^”]+[...
def cleanwikicode(text): if not text: return ""
if not mysite.loggedin(): print "You must be logged in to upload images" import sys sys.exit(1)
def main(give_url,image_url): url = give_url basicdesc = [] 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 check (use $ for the part that is changeable)") else: url = wikipedia.input(u"From wha...
answer =wikipedia.input(u"Include image %s (y/N/s(top))?"%image)
answer = wikipedia.inputChoice(u'Include image %s?' % image, ['yes', 'no', 'stop'], ['y', 'N', 's'], 'N')
def main(give_url,image_url): url = give_url basicdesc = [] 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 check (use $ for the part that is changeable)") else: url = wikipedia.input(u"From wha...
lib_images.get_image(image, None, desc)
uploadBot = upload.UploadRobot(image, desc) uploadBot.run()
def main(give_url,image_url): url = give_url basicdesc = [] 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 check (use $ for the part that is changeable)") else: url = wikipedia.input(u"From wha...
url = ''
url = u''
def main(give_url,image_url): url = give_url basicdesc = [] 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 check (use $ for the part that is changeable)") else: url = wikipedia.input(u"From wha...
if wikipedia.argHandler(arg, 'imageharvest'):
arg = wikipedia.argHandler(arg, 'imageharvest') if arg:
def main(give_url,image_url): url = give_url basicdesc = [] 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 check (use $ for the part that is changeable)") else: url = wikipedia.input(u"From wha...
elif url == '':
elif url == u'':
def main(give_url,image_url): url = give_url basicdesc = [] 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 check (use $ for the part that is changeable)") else: url = wikipedia.input(u"From wha...
self.version = '1.5'
def version(self, code): return "1.5"
def __init__(self): family.Family.__init__(self) self.name = 'commons' self.langs = { 'commons': 'commons.wikimedia.org', } self.namespaces[4] = { '_default': 'Commons', } self.namespaces[5] = { '_default': 'Commons talk', }
print mediawiki_messages.get('spamprotectiontitle', self.site())
output(u""+mediawiki_messages.get('spamprotectiontitle', self.site()))
def putPage(self, text, comment = None, watchArticle = False, minorEdit = True, newPage = False, token = None, gettoken = False, sysop = False): """ Upload 'text' as new contents for this Page by filling out the edit page.
if code in ['eml','lij','lmo','nap','pms','roa-tará','sc','scn','vec']:
if code in ['eml','lij','lmo','nap','pms','roa-tara','sc','scn','vec']:
def altlang(code): if code=='aa': return ['am'] if code in ['fa','so']: return ['ar'] if code=='ku': return ['ar','tr'] if code=='sk': return ['cs'] if code in ['bar','hsb','ksh']: return ['de'] if code in ['als','lb']: return ['de','fr'] if code=='io': return ['eo'] if code in ['an','ast','ay','ca','gn','nah','qu']: r...
def showdiff(old, new):
def showdiff(self,old, new):
def showdiff(old, new): diff = difflib.context_diff(old.splitlines(), new.splitlines()) wikipedia.output(u"\n".join(diff))
raise
wikipedia.stopme()
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...
return "[[user:%s" % username in text.lower()
return "[[user:%s" % username.lower() in text.lower()
def allowedbot(username, site): """Checks whether the bot is listed on Wikipedia:bots""" pl = wikipedia.Page(site, "Wikipedia:Bots") text = pl.get() return "[[user:%s" % username in text.lower()
catlib.change_category(article, original_cat, None)
catlib.change_category(article, original_cat.catname(), None)
def move_to_subcategory(article, original_cat, current_cat): print print 'Treating page ' + article.ascii_linkname() + ', currently in category ' + current_cat.ascii_linkname() subcatlist = get_subcats(current_cat) print if len(subcatlist) == 0: print 'This category has no subcategories.' print # show subcategories as ...
ns = mysite.template_namespace(fallback = None)
ns = mysite.template_namespace()
def main(): template_names = [] resolve = False remove = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'template') if arg: if arg == '-remove': remove = True elif arg.sta...