rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
def setpage(self, new): """Sets page and pagelink"""
def setpage(self): """Sets page and page title""" site = wikipedia.getSite()
def setpage(self, new): """Sets page and pagelink""" pageTitle = self.options.page or wikipedia.input(u"Page to edit:") self.page = wikipedia.Page(self.site, pageTitle) if not self.options.edit_redirect and self.page.isRedirectPage(): self.page = wikipedia.Page(self.site, self.page.getRedirectTarget())
self.page = wikipedia.Page(self.site, pageTitle)
self.page = wikipedia.Page(site, pageTitle)
def setpage(self, new): """Sets page and pagelink""" pageTitle = self.options.page or wikipedia.input(u"Page to edit:") self.page = wikipedia.Page(self.site, pageTitle) if not self.options.edit_redirect and self.page.isRedirectPage(): self.page = wikipedia.Page(self.site, self.page.getRedirectTarget())
self.page = wikipedia.Page(self.site, self.page.getRedirectTarget())
self.page = wikipedia.Page(site, self.page.getRedirectTarget())
def setpage(self, new): """Sets page and pagelink""" pageTitle = self.options.page or wikipedia.input(u"Page to edit:") self.page = wikipedia.Page(self.site, pageTitle) if not self.options.edit_redirect and self.page.isRedirectPage(): self.page = wikipedia.Page(self.site, self.page.getRedirectTarget())
self.initialise_data()
def run(self): self.initialise_data() try: old = self.page.get(get_redirect = self.options.edit_redirect) except wikipedia.NoPage: old = "" textEditor = TextEditor(self.options) new = textEditor.edit(old) if new and old != new: new = self.repair(new) wikipedia.showDiff(old, new) comment = wikipedia.input(u"What did you...
textEditor = TextEditor(self.options)
textEditor = TextEditor()
def run(self): self.initialise_data() try: old = self.page.get(get_redirect = self.options.edit_redirect) except wikipedia.NoPage: old = "" textEditor = TextEditor(self.options) new = textEditor.edit(old) if new and old != new: new = self.repair(new) wikipedia.showDiff(old, new) comment = wikipedia.input(u"What did you...
name = url2unicode(name, language = code)
try: name = url2unicode(name, language = code) except UnicodeEncodeError: name = html2unicode(name, language = code, altlanguage = incode)
def link2url(name, code, incode = None): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link""" if '%' in name: name = url2unicode(name, language = code) else: name = html2unicode(name, language = code, altlanguage = incode) #pri...
self.maxdelay = delay
def setDelay(self, delay = config.minthrottle, absolute = False): if absolute: self.mindelay = delay self.maxdelay = delay self.delay = delay # Don't count the time we already waited as part of our waiting time :-0 self.now = time.time()
allNotFound = True
def run(self): dt=15 while True: try: data = self.getData() except (socket.error, httplib.BadStatusLine): # Print the traceback of the caught exception print ''.join(traceback.format_exception(*sys.exc_info())) output(u'DBG> got network error in GetAll.run. Sleeping for %d seconds'%dt) time.sleep(dt) if dt <= 60: dt +=...
else: allNotFound = False if allNotFound: f = codecs.open('pageNotFound.txt', 'a', 'utf-8') f.write(' f.write(' f.write(' f.write('%s\n' % self.pages) f.write('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n') f.write('%s\n' % data) f.write(' f.close()
def run(self): dt=15 while True: try: data = self.getData() except (socket.error, httplib.BadStatusLine): # Print the traceback of the caught exception print ''.join(traceback.format_exception(*sys.exc_info())) output(u'DBG> got network error in GetAll.run. Sleeping for %d seconds'%dt) time.sleep(dt) if dt <= 60: dt +=...
cats = pl.categories(withSortKeys = True)
cats = pl.categories()
def include(pl,checklinks=True,realinclude=True,linkterm=None): cl = checklinks if realinclude: try: text = pl.get() except wikipedia.NoPage: pass except wikipedia.IsRedirectPage: cl = True pass else: cats = pl.categories() if not workingcat in cats: cats = pl.categories(withSortKeys = True) for c in cats: if rawtoclea...
if rawtoclean(c) in parentcats: cats.remove(c) if linkterm: pl.put(wikipedia.replaceCategoryLinks(text, cats + [wikipedia.Page(mysite,"%s|%s"%(workingcat.title(),linkterm))]))
if c in parentcats: catlib.change_category(pl,c,workingcat) break
def include(pl,checklinks=True,realinclude=True,linkterm=None): cl = checklinks if realinclude: try: text = pl.get() except wikipedia.NoPage: pass except wikipedia.IsRedirectPage: cl = True pass else: cats = pl.categories() if not workingcat in cats: cats = pl.categories(withSortKeys = True) for c in cats: if rawtoclea...
print print("==%s==")%pl.title()
wikipedia.output(u'') wikipedia.output(u"==%s=="%pl.title())
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print("t: Give the beginning of the text of the page") print("z: Add under another title (as [[Category|Title]])") print("x: Add the page, but do not check links to and from it") print("c: Do not add the page, but do check links") print("a: Add another page") print("l: Give a list of the pages to check")
wikipedia.output(u"t: Give the beginning of the text of the page") wikipedia.output(u"z: Add under another title (as [[Category|Title]])") wikipedia.output(u"x: Add the page, but do not check links to and from it") wikipedia.output(u"c: Do not add the page, but do check links") wikipedia.output(u"a: Add another page") ...
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print("Redirect page. Will be included normally.")
wikipedia.output(u"Redirect page. Will be included normally.")
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print("Page does not exist; not added.")
wikipedia.output(u"Page does not exist; not added.")
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print("Number of pages still to check: %s")%len(tocheck) print("Pages to be checked:") print tocheck print("==%s==")%pl.title()
wikipedia.output(u"Number of pages still to check: %s"%len(tocheck)) wikipedia.output(u"Pages to be checked:") wikipedia.output(u" - ".join(page.title() for page in tocheck)) wikipedia.output(u"==%s=="%pl.title())
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print("==%s==")%pl.title()
wikipedia.output(u"==%s=="%pl.title())
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
wikipedia.output(pl.get(get_redirect=True)[0:ctoshow])
wikipedia.output(u''+pl.get(get_redirect=True)[0:ctoshow])
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print "Page does not exist."
wikipedia.output(u"Page does not exist.")
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print("Not understood.")
wikipedia.output(u"Not understood.")
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
workingcat = catlib.Category(mysite,workingcatname)
workingcat = catlib.Category(mysite,mysite.category_namespace()+':'+workingcatname)
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
print answer
wikipedia.output(u''+answer)
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
if not checkbackward:
if not checkbroken:
def asktoadd(pl): ctoshow = 500 print print("==%s==")%pl.title() while 1: answer = raw_input("y(es)/n(o)/i(gnore)/(o)ther options? ") if answer=='y': include(pl) break if answer=='c': include(pl,realinclude=False) break if answer=='z': if pl.exists(): if not pl.isRedirectPage(): linkterm = wikipedia.input(u"In what man...
self.seriouslangs = biglangs4
self.seriouslangs = self.biglangs4
def __init__(self): family.Family.__init__(self) self.name = 'wiktionary' self.langs = { 'minnan':'zh-min-nan.wiktionary.org', 'nb':'no.wiktionary.org', 'zh-cn':'zh.wiktionary.org', 'zh-tw':'zh.wiktionary.org' } for lang in self.knownlanguages: self.langs[lang] = lang+'.wiktionary.org' # Most namespaces are inherited...
if replaceit or new_page_title == link_text:
if replaceit and trailing_chars: newlink = "[[%s]]%s" % (new_page_title, trailing_chars) elif new_page_title == link_text or replaceit:
def treat(refpl, thispl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: wikipedia.output(u'%s is a redirect to %s' % (refpl.linkname(), thispl.linkname())) choice = wikipedia.input(u'Do you want to work on pages linking to %s? [y|N]' % refpl.linkname()) if choice == 'y': for ref_redir in getReferences(refpl)...
self.inPlace = inPlace
def __init__(self, oldCatTitle, newCatTitle, batchMode = False, editSummary = '', inPlace = False, moveCatPage = True): self.editSummary = editSummary self.inPlace = inPlace self.oldCat = catlib.Category(wikipedia.getSite(), 'Category:' + oldCatTitle) self.newCatTitle = newCatTitle self.inPlace = inPlace self.moveCatPa...
catlib.change_category(subcategory, self.oldCat, newCat, inPlace=inPlace)
catlib.change_category(subcategory, self.oldCat, newCat, inPlace=self.inPlace)
def run(self): newCat = catlib.Category(wikipedia.getSite(), 'Category:' + self.newCatTitle) gen = pagegenerators.CategorizedPageGenerator(self.oldCat, recurse = False) preloadingGen = pagegenerators.PreloadingGenerator(gen) for article in preloadingGen: catlib.change_category(article, self.oldCat, newCat, inPlace=self...
redirR = re.compile('
redirR = wikipedia.redirectRe(wikipedia.mylang)
def get_redirects_from_dump(sqlfilename): dict = {} # open sql dump and read page titles out of it dump = sqldump.SQLdump(sqlfilename, wikipedia.myencoding()) # case-insensitive regular expression which takes a redirect's text # (that is: '#REDIRECT [[bla]]') and extracts its target (that is: bla). redirR = re.compile(...
if entry.redirect == '1':
if entry.redirect:
def get_redirects_from_dump(sqlfilename): dict = {} # open sql dump and read page titles out of it dump = sqldump.SQLdump(sqlfilename, wikipedia.myencoding()) # case-insensitive regular expression which takes a redirect's text # (that is: '#REDIRECT [[bla]]') and extracts its target (that is: bla). redirR = re.compile(...
print 'NOTE: This function is not working yet. Press Enter to continue.' raw_input()
def retrieve_broken_redirects(source): if source == None: # retrieve information from the live wiki's maintenance page host = wikipedia.family.hostname(wikipedia.mylang) # broken redirect maintenance page's URL url = wikipedia.family.maintenance_address(wikipedia.mylang, 'brokenredirects', default_limit = False) print ...
pagetitles = []
pagetitles = {}
def retrieve_broken_redirects(source): if source == None: # retrieve information from the live wiki's maintenance page host = wikipedia.family.hostname(wikipedia.mylang) # broken redirect maintenance page's URL url = wikipedia.family.maintenance_address(wikipedia.mylang, 'brokenredirects', default_limit = False) print ...
print entry.full_title() pagetitles.append(entry.full_title()) print 'Step 3: Comparing. This might take a while (or two).'
pagetitles[entry.full_title()] = None print 'Step 3: Comparing.'
def retrieve_broken_redirects(source): if source == None: # retrieve information from the live wiki's maintenance page host = wikipedia.family.hostname(wikipedia.mylang) # broken redirect maintenance page's URL url = wikipedia.family.maintenance_address(wikipedia.mylang, 'brokenredirects', default_limit = False) print ...
for (key, value) in redirs.popitem(): print key if not value in pagetitles: brokenredirs.append(key) print brokenredirs
for (key, value) in redirs.iteritems(): if not pagetitles.has_key(value): yield key
def retrieve_broken_redirects(source): if source == None: # retrieve information from the live wiki's maintenance page host = wikipedia.family.hostname(wikipedia.mylang) # broken redirect maintenance page's URL url = wikipedia.family.maintenance_address(wikipedia.mylang, 'brokenredirects', default_limit = False) print ...
except (wikipedia.IsNotRedirectPage, wikipedia.NoPage): wikipedia.output('%s doesn\'t exist or is not a redirect.')
except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir_page.linkname()) except wikipedia.NoPage: wikipedia.output(u'%s doesn\'t exist.' % redir_page.linkname())
def delete_broken_redirects(source): # get reason for deletion text reason = reason_broken[wikipedia.chooselang(wikipedia.mylang, reason_broken)] for redir_name in retrieve_broken_redirects(source): redir_page = wikipedia.PageLink(wikipedia.mylang, redir_name) try: target_page = redir_page.getRedirectTo() except (wiki...
except wikipedia.IsRedirectPage(): wikipedia.output('Redirect target is also a redirect! Won\'t delete anything.')
except wikipedia.IsRedirectPage: wikipedia.output(u'Redirect target is also a redirect! Won\'t delete anything.')
def delete_broken_redirects(source): # get reason for deletion text reason = reason_broken[wikipedia.chooselang(wikipedia.mylang, reason_broken)] for redir_name in retrieve_broken_redirects(source): redir_page = wikipedia.PageLink(wikipedia.mylang, redir_name) try: target_page = redir_page.getRedirectTo() except (wiki...
wikipedia.output('Redirect target does exist! Won\'t delete anything.')
wikipedia.output(u'Redirect target does exist! Won\'t delete anything.')
def delete_broken_redirects(source): # get reason for deletion text reason = reason_broken[wikipedia.chooselang(wikipedia.mylang, reason_broken)] for redir_name in retrieve_broken_redirects(source): redir_page = wikipedia.PageLink(wikipedia.mylang, redir_name) try: target_page = redir_page.getRedirectTo() except (wiki...
second_redir = wikipedia.PageLink(wikipedia.mylang, target) second_target = str(second_redir.getRedirectTo()) except (wikipedia.IsNotRedirectPage, wikipedia.NoPage): print 'The specified page is not a double redirect.\n' continue txt = " redir.put(txt) print ''
except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir.linkname()) except wikipedia.NoPage: wikipedia.output(u'%s doesn\'t exist.' % redir.linkname()) except wikipedia.LockedPage: wikipedia.output(u'%s is locked, skipping.' % redir.linkname()) else: try: second_redir = wikipedia.PageLink(...
def fix_double_redirects(source): for redir_name in retrieve_double_redirects(source): redir = wikipedia.PageLink(wikipedia.mylang, redir_name) try: target = str(redir.getRedirectTo()) second_redir = wikipedia.PageLink(wikipedia.mylang, target) second_target = str(second_redir.getRedirectTo()) except (wikipedia.IsNotRe...
sqlfilename = wikipedia.input('Please enter the SQL dump\'s filename: ')
sqlfilename = wikipedia.input(u'Please enter the SQL dump\'s filename: ')
def fix_double_redirects(source): for redir_name in retrieve_double_redirects(source): redir = wikipedia.PageLink(wikipedia.mylang, redir_name) try: target = str(redir.getRedirectTo()) second_redir = wikipedia.PageLink(wikipedia.mylang, target) second_target = str(second_redir.getRedirectTo()) except (wikipedia.IsNotRe...
password = getpass.getpass(u'password: ')
password = getpass.getpass('password: ')
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...
colors += [color[lastline[0]] for c in lastline] + [None]
lastcolors = [None for c in lastline] lastcolors[0] = color[lastline[0]] colors += lastcolors + [None]
def showDiff(oldtext, newtext): """ Prints a string showing the differences between oldtext and newtext. The differences are highlighted (only on Unix systems) to show which changes were made. """ # For information on difflib, see http://pydoc.org/2.3/difflib.html color = { '+': 10, # green '-': 12 # red } diff = '' c...
sysop = (not self.editRestriction)
sysop = not not self.editRestriction
def put(self, newtext, comment=None, watchArticle = None, 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
return x
return x, isWatched
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 Page object instead. Arguments: site - the wiki site name ...
wikipedia.output(u"* %s" % cat.aslink())
wikipedia.output(u"* %s" % pl.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...
print 'WARNING: can\'t extract the target of redirect %s, ignoring' % (entry.full_title())
wikipedia.output(u'WARNING: can\'t extract the target of redirect %s, ignoring' % (entry.full_title()))
def get_redirects_from_dump(sqlfilename): ''' Loads a local sql dump file, looks at all pages which have the redirect flag set, and finds out where they're pointing at. Returns a dictionary where the redirect names are the keys and the redirect targets are the values. NOTE: if the redirect isn't in the main namespace, ...
redir.put(txt)
status, reason, data = redir.put(txt) print status, reason
def fix_double_redirects(source): mysite = wikipedia.getSite() for redir_name in retrieve_double_redirects(source): print '' redir = wikipedia.PageLink(mysite, redir_name) try: target = redir.getRedirectTo() except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir.linkname()) except wikiped...
wikipedia.output(u"Killing remaining %i threads, please wait..." % (threading.activeCount() - 2))
wikipedia.output(u'Remaining %i thread will be killed.' % (threading.activeCount() - 2)) wikipedia.output(u'Saving history...') bot.history.save()
def main(): start = u'!' pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'weblinkchecker') if arg: if arg.startswith('-start:'): start = arg[7:] else: pageTitle.append(arg) if pageTitle == []: gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle = ' '.join(pageTitle) page = wikiped...
while bot.history.reportThread.isAlive(): time.sleep(0.1) bot.history.save()
while bot.history.reportThread.isAlive(): time.sleep(0.1)
def main(): start = u'!' pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'weblinkchecker') if arg: if arg.startswith('-start:'): start = arg[7:] else: pageTitle.append(arg) if pageTitle == []: gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle = ' '.join(pageTitle) page = wikiped...
if old[site] != new[site]:
if site not in new: removing.append(site) elif old[site] != new[site]:
def compareLanguages(old, new): removing = [] adding = [] modifying = [] mysite = wikipedia.getSite() for site in old.keys(): if old[site] != new[site]: modifying.append(site) for site2 in new.keys(): if site2 not in old: adding.append(site2) s = "" if adding: s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[0]...
linkR = re.compile(r'http[s]?://[^\]\s<>}"]*?[^\]\s\)\.:;,<>}"](?=\'\')|http[s]?://[^\]\s<>}"]*[^\]\s\)\.:;,<>}"]')
linkR = re.compile(r'http[s]?://[^\]\s<>}"]*?[^\]\s\)\.:;,<>}\|"](?=\'\')|http[s]?://[^\]\s<>}"]*[^\]\s\)\.:;,<>}"\|]')
def checkLinksIn(self, page): try: text = page.get() except wikipedia.NoPage: wikipedia.output(u'%s does not exist.' % page.title()) return # 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...
source = None
xmlfilename = None textfilename = None
def main(): quietMode = False # use -quiet to get less output # if the -file argument is used, page titles are stored in this array. # otherwise it will only contain one page. articles = [] # if -file is not used, this temporary array is used to read the page title. page_title = [] debug = False source = None for arg i...
f=open(arg[6:], 'r') R=re.compile(r'.*\[\[([^\]]*)\]\].*') m = False for line in f.readlines(): m=R.match(line) if m: articles.append(m.group(1)) else: print "ERROR: Did not understand %s line:\n%s" % ( arg[6:], repr(line)) f.close()
if len(arg) == 5: textfilename = wikipedia.input(u'Please enter the textfile\'s name:') else: textfilename = arg[6:]
def main(): quietMode = False # use -quiet to get less output # if the -file argument is used, page titles are stored in this array. # otherwise it will only contain one page. articles = [] # if -file is not used, this temporary array is used to read the page title. page_title = [] debug = False source = None for arg i...
source = 'xmldump'
def main(): quietMode = False # use -quiet to get less output # if the -file argument is used, page titles are stored in this array. # otherwise it will only contain one page. articles = [] # if -file is not used, this temporary array is used to read the page title. page_title = [] debug = False source = None for arg i...
if source == 'xmldump': gen = pagegenerators.PreloadingGenerator(TableXmlDumpPageGenerator(xmlfilename))
if xmlfilename: gen = TableXmlDumpPageGenerator(xmlfilename) elif textfilename: gen = pagegenerators.TextfilePageGenerator(textfilename)
def main(): quietMode = False # use -quiet to get less output # if the -file argument is used, page titles are stored in this array. # otherwise it will only contain one page. articles = [] # if -file is not used, this temporary array is used to read the page title. page_title = [] debug = False source = None for arg i...
gen = pagegenerators.PreloadingGenerator(iter([page]))
gen = iter([page])
def main(): quietMode = False # use -quiet to get less output # if the -file argument is used, page titles are stored in this array. # otherwise it will only contain one page. articles = [] # if -file is not used, this temporary array is used to read the page title. page_title = [] debug = False source = None for arg i...
bot = Table2WikiRobot(gen, debug, quietMode)
preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = Table2WikiRobot(preloadingGen, debug, quietMode)
def main(): quietMode = False # use -quiet to get less output # if the -file argument is used, page titles are stored in this array. # otherwise it will only contain one page. articles = [] # if -file is not used, this temporary array is used to read the page title. page_title = [] debug = False source = None for arg i...
s = StringIO.StringIO(data) rImage = re.compile('.*<a href="/wiki/.*?:(.*?)".*?[\n]*?.*?class="internal"') rThumb = re.compile('.*<a href="/wiki/.*?:(.*?)".*?class="image"')
rImage = re.compile('<a href=[\r\n]*?"/wiki/.*?:(.*?)".*?[\r\n]*?.*?class=[\r\n]*?"image"', re.MULTILINE)
def extractImages(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 """ images = [] s = StringIO.StringIO(data) rImage = re.compile('.*<a href="/wiki/.*?:(.*?)".*?[\n]*?.*?class="internal"'...
for line in s: img = rImage.match(line) try: path = md5.new(html2txt(img.group(1))).hexdigest() if path != last: images.append( {'image':img.group(1), 'path': str(path[0])+"/"+str(path[0:2])+"/"}) last = path except: pass img = rThumb.match(line) try: path = md5.new(html2txt(img.group(1))).hexdigest() if path != las...
img = rImage.findall(data) print "Bilder: ", img for image in img: path = md5.new(html2txt(image)).hexdigest() images.append( {'image': image, 'path' : str(path[0])+"/"+str(path[0:2])+"/"})
def extractImages(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 """ images = [] s = StringIO.StringIO(data) rImage = re.compile('.*<a href="/wiki/.*?:(.*?)".*?[\n]*?.*?class="internal"'...
try: main() conn.close() except: wikipedia.stopme() raise else: wikipedia.stopme()
main()
def main(): mysite = wikipedia.getSite() sa = [] output_directory = "" save_images = False overwrite_images = False overwrite_articles = False for arg in sys.argv[1:]: if arg.startswith("-lang:"): lang = arg[6:] elif arg.startswith("-file:"): f=open(arg[6:], 'r') R=re.compile(r'.*\[\[([^\]]*)\]\].*') m = False for lin...
return urllib.quote(self.title())
encodedTitle = self.title().encode(self.site().encoding()) return urllib.quote(encodedTitle)
def urlname(self): """The name of the page this Page refers to, in a form suitable for the URL of the page.""" return urllib.quote(self.title())
edittime[self.site, title] = timestamp
edittime[self.site, pl.urlname()] = timestamp
def oneDone(self, title, timestamp, text): pl = Page(self.site, title) for pl2 in self.pages: if Page(self.site, pl2.sectionFreeTitle()) == 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: page not found in list"
if watchArticle and watchArticle != '0':
if watchArticle:
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...
targetTitle = self.targetSite.image_namespace() + image.title().split(':', 1)[1]
targetTitle = '%s:%s' % (self.targetSite.image_namespace(), image.title().split(':', 1)[1])
def run(self): for page in self.generator: if self.interwiki: imagelist = [] for linkedPage in page.interwiki(): imagelist += linkedPage.imagelinks(followRedirects = True) elif page.isImage(): imagelist = [page] else: imagelist = page.imagelinks(followRedirects = True)
for i in range(len(refs)):
for i in range(len(refs)-1, -1, -1):
def getReferences(self): refs = self.disambPl.getReferences(follow_redirects = False) wikipedia.output(u"Found %d references." % len(refs)) # Remove ignorables if ignore_title.has_key(self.disambPl.site().lang): for ig in ignore_title[self.disambPl.site().lang]: for i in range(len(refs)): if re.match(ig, refs[i].linkna...
if choice[0] == 'r':
if len(choice)>0 and choice[0] == 'r':
def treat(refpl, thispl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: wikipedia.output('%s is a redirect to %s' % (refpl.linkname(), thispl.linkname())) choice = wikipedia.input('Do you want to work on pages linking to %s? [y|N]' % refpl.linkname()) if choice == 'y': for ref_redir in getReferences(refpl): ...
yield PageLink(mylang, hit)
if family.version(mylang)=="1.2": yield PageLink(mylang, url2link(hit, code = mylang, incode = mylang)) else: yield PageLink(mylang, hit)
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...
if newPage:
if newPage=='1':
def putPage(code, name, text, comment = None, watchArticle = '0', minorEdit = '1', newPage = '0'): """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.put_...
if globalvar.shownew: wikipedia.output(u"%s: %s gives new interwiki %s"% (self.originPage.aslink(), page.aslink(True), linkedPage.aslink(True)))
lpsite=linkedPage.site() for prevPage in self.foundIn.keys(): if prevPage != linkedPage and prevPage.site() == lpsite: self.problem(u"%s: %s gives duplicate interwiki on same site %s" % (self.originPage.aslink(), page.aslink(True), linkedPage.aslink(True))) if globalvar.autonomous: self.todo = [] return break else: i...
def workDone(self, counter): """ This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo. """ # Loop over all the pages that should have been taken care o...
errorCount = 0
errorCount = self.problemfound
def assemble(self): # No errors have been seen so far errorCount = 0 mysite = wikipedia.getSite() # Build up a dictionary of all pages found, with the site as key. # Each value will be a list of pages. new = {} for page in self.done: site = page.site() if site == mysite and page.exists() and not page.isRedirectPage(): ...
assert charsets[code]==charset,"charset for %s changed from %s to %s"%(code,charsets(code),charset)
assert charsets[code].lower()==charset.lower(),"charset for %s changed from %s to %s"%(code,charsets[code],charset)
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('...
del self.historyDict[url]
try: del self.historyDict[url] except KeyError: pass
def setLinkAlive(self, url): """ If the link was previously found dead, removes it from the .dat file and returns True, else returns False. """ if self.historyDict.has_key(url): self.semaphore.acquire() del self.historyDict[url] self.semaphore.release() return True else: return False
return [catlib.Category(self.site(), title) for title in categoryTitles]
return [catlib.Category(self.site(), ':'.join(title.split(':')[1:])) for title in categoryTitles]
def categories(self, withSortKeys = False): """ 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. The return value is a list of Category objects, one for each of the category links in the page text.
elif len(new_page_title) <= len(link_text) and link_text[:len(new_page_title)] == new_page_title:
elif len(new_page_title) <= len(link_text) and link_text[:len(new_page_title)] == new_page_title and re.sub(trailR, '', link_text[len(new_page_title):]) == '':
def treat(refpl, thispl): try: reftxt=refpl.get() except wikipedia.IsRedirectPage: pass else: n = 0 curpos = 0 while 1: m=linkR.search(reftxt, pos = curpos) if not m: if n == 0: print "Not found in %s"%refpl elif not debug: refpl.put(reftxt) return True # Make sure that next time around we will not find this same hit. ...
if line[i] != ' ':
if line[i] != ' ' and i<len(line)-1:
def printLastLine(lastline, lastcolor): # highlight the minus red or the plus green if lastline != None: lastline = '\x1b[' + lastcolor + ';1m' + lastline[0] + '\x1b[0m' + lastline[1:] output(lastline)
if site.version() >= "1.8": itemR = re.compile('<tr class="def" id=".*?">' + '\s*<td>' + '\s*<a id=".+?" name=".+?"></a>' + '\s*<a href=".+?" title=".+?"><span id=\".*?\">(?P<key>.+?)</span></a><br />' + '\s*<a href=".+?"( class="new")? title=".+?">.+?</a>' + '\s*</td><td>' + '\s*(?P<current>.+?)' + '\s*</td>' + '\s*</...
if site.version() >= "1.5": itemR = re.compile("<tr class=('|\")def('|\") id=('|\").*?('|\")>\n"
def refresh_messages(site = None): site = site or wikipedia.getSite() # get 'all messages' special page's path path = site.allmessages_address() print 'Retrieving MediaWiki messages for %s' % repr(site) wikipedia.put_throttle() # It actually is a get, but a heavy one. allmessages = site.getUrl(path) print 'Parsing Med...
+ '\s*<a href=".+?" title=".+?"><span id=\'.*?\'>(?P<key>.+?)</span><\/a><br \/>'
+ '\s*<a href=".+?" title=".+?"><span id=(\'|").*?(\'|")>(?P<key>.+?)</span><\/a><br \/>'
def refresh_messages(site = None): site = site or wikipedia.getSite() # get 'all messages' special page's path path = site.allmessages_address() print 'Retrieving MediaWiki messages for %s' % repr(site) wikipedia.put_throttle() # It actually is a get, but a heavy one. allmessages = site.getUrl(path) print 'Parsing Med...
+ "<tr class='orig' id='.*?'>\n" + "\s*<td rowspan='2'>"
+ "<tr class=('|\")orig('|\") id=('|\").*?('|\")>\n" + "\s*<td rowspan=('|\")2('|\")>"
def refresh_messages(site = None): site = site or wikipedia.getSite() # get 'all messages' special page's path path = site.allmessages_address() print 'Retrieving MediaWiki messages for %s' % repr(site) wikipedia.put_throttle() # It actually is a get, but a heavy one. allmessages = site.getUrl(path) print 'Parsing Med...
+ '\s*<a href=".+?" title=".+?"><span id=\'.*?\'>(?P<key2>.+?)</span><\/a><br \/>'
+ '\s*<a href=".+?" title=".+?"><span id=(\'|").*?(\'|")>(?P<key2>.+?)</span><\/a><br \/>'
def refresh_messages(site = None): site = site or wikipedia.getSite() # get 'all messages' special page's path path = site.allmessages_address() print 'Retrieving MediaWiki messages for %s' % repr(site) wikipedia.put_throttle() # It actually is a get, but a heavy one. allmessages = site.getUrl(path) print 'Parsing Med...
+ "\s*</tr><tr class='new' id='.*?'>"
+ "\s*</tr><tr class=('|\")new('|\") id=('|\").*?('|\")>"
def refresh_messages(site = None): site = site or wikipedia.getSite() # get 'all messages' special page's path path = site.allmessages_address() print 'Retrieving MediaWiki messages for %s' % repr(site) wikipedia.put_throttle() # It actually is a get, but a heavy one. allmessages = site.getUrl(path) print 'Parsing Med...
elif arg == '-home': refresh_messages()
def main(): debug = False refresh_all = False for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'mediawiki_messages') if arg: if arg == '-debug': debug = True elif arg == '-all': refresh_all = True if refresh_all: refresh_all_messages() else: refresh_messages(wikipedia.getSite()) if debug: print "DBG> successfu...
},
}
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...
raise self._getexception
if self._getexception == IsRedirectPage and get_redirect: pass else: raise self._getexception
def get(self, force = False, get_redirect=False, throttle = True, sysop = False): """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:
ImageRegex = re.compile(r'\[\[ *[Ii]mage:' + old + ' *(?P<parameters>\|[^}]+|) *\]\]')
ImageRegex = re.compile(r'\[\[ *[Ii]mage:' + old + ' *(?P<parameters>\|[^\n]+|) *\]\]')
def run(self): """ Starts the robot's action. """ # regular expression to find the original template. # {{vfd}} does the same thing as {{Vfd}}, so both will be found. # The old syntax, {{msg:vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none.
def hashfreeLinkname(self): hn=self.hashname() if hn: return self.linkname()[:-len(hn)+1] else: return self.linkname()
def hashname(self): """The name of the subpage this PageLink refers to. Subpages are denominated by a # in the linkname(). If no subpage is referenced, None is returned.""" ln = self.linkname() ln = re.sub('&#', '&hash;', ln) if not '#' in ln: return None else: hn = ln[ln.find('#') + 1:] hn = re.sub('&hash;', '&#', hn)...
class WikimediaXmlHandler(xml.sax.handler.ContentHandler): def setCallback(self, callback): self.callback = callback def startElement(self, name, attrs): self.destination = None if name == 'page': self.text=u'' self.title=u'' self.timestamp=u'' elif name == 'text': self.destination = 'text' elif name == 'title': self....
def getRedirectTo(self):
Rredirect = re.compile(r'\
def getPage(code, name, do_edit = 1, do_quote = 1): """Get the contents of page 'name' from the 'code' language wikipedia Do not use this directly; use the PageLink object instead.""" host = langs[code] if code in oldsoftware: # Old algorithm name = re.sub('_', ' ', name) n = [] for x in name.split(): n.append(x[0].cap...
replacements.append(commandline_replacements[0], commandline_replacements[1])
replacements.append((commandline_replacements[0], commandline_replacements[1]))
def main(): # 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-tu...
replacements.append(old, new)
replacements.append((old, new))
def main(): # 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-tu...
text = text.encode(myencoding())
text = text.encode(code2encoding(code))
def forCode(text, code): """Prepare the unicode string 'text' for inclusion into a page for language 'code'. All of the characters in the text should be encodable, otherwise this will fail! This condition is normally met, except if you would copy text verbatim from an UTF-8 language into a iso-8859-1 language, and none...
x=urllib.unquote(percentname)
for c in percentname: if ord(c)>128: x=percentname break else: x=urllib.unquote(str(percentname))
def url2unicode(percentname, language): x=urllib.unquote(percentname) #print "DBG> ",language,repr(percentname),repr(x) # Try utf-8 first. It almost cannot succeed by accident! for encoding in ('utf-8',)+code2encodings(language): try: encode_func, decode_func, stream_reader, stream_writer = codecs.lookup(encoding) x,l ...
sourceImagePage.put(original_description + '\n\n' + nowCommonsTemplate[sourceSite.lang][0] % targetFilename, comment = nowCommonsMessage[sourceSite.lang][1])
sourceImagePage.put(original_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 ...
path = self.get_address('Non-existing page')
path = self.get_address('Non-existing_page')
def loggedin(self, check = False): if not hasattr(self,'_loggedin'): self._fill() if check: path = self.get_address('Non-existing page') txt = getUrl(self, path) self._loggedin = 'Userlogin' not in txt return self._loggedin
ok, message = linkChecker.check()
try: ok, message = linkChecker.check() except: wikipedia.output('Exception while processing URL %s in page %s' % (self.url, self.title)) raise
def run(self): linkChecker = LinkChecker(self.url) ok, message = linkChecker.check() if ok: if self.history.setLinkAlive(self.url): wikipedia.output('*Link to %s in [[%s]] is back alive.' % (self.url, self.title)) else: wikipedia.output('*[[%s]] links to %s - %s.' % (self.title, self.url, message)) self.history.setLink...
cats = pl.categories(catsWithSortKeys = True)
cats = pl.categories(withSortKeys = True)
def include(pl,checklinks=True,realinclude=True,linkterm=None): cl = checklinks if realinclude: try: text = pl.get() except wikipedia.NoPage: pass except wikipedia.IsRedirectPage: cl = True pass else: cats = pl.categories() if not workingcat in cats: cats = pl.categories(catsWithSortKeys = True) for c in cats: if rawto...
output(u'Page %s is semi-protected. Getting edit page to find out if we are allowed to edit.' % self)
output(u'Page %s is semi-protected. Getting edit page to find out if we are allowed to edit.' % self.aslink())
def put(self, newtext, comment=None, watchArticle = None, 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
x=urllib.unquote(percentname)
x=urllib.unquote(str(percentname))
def url2unicode(percentname, language): x=urllib.unquote(percentname) for encoding in code2encodings(language): try: encode_func, decode_func, stream_reader, stream_writer = codecs.lookup(encoding) x,l = decode_func(x) return x except UnicodeError: pass raise UnicodeError("Could not decode %s" % repr(percentname))
x,l = encode_func(x)
y,l = encode_func(x)
def unicode2html(x, encoding='latin1'): # We have a unicode string. We can attempt to encode it into the desired # format, and if that doesn't work, we encode the unicode into html # # entities. try: encode_func, decode_func, stream_reader, stream_writer = codecs.lookup(encoding) x,l = encode_func(x) except UnicodeErro...
return str(x)
return x
def unicode2html(x, encoding='latin1'): # We have a unicode string. We can attempt to encode it into the desired # format, and if that doesn't work, we encode the unicode into html # # entities. try: encode_func, decode_func, stream_reader, stream_writer = codecs.lookup(encoding) x,l = encode_func(x) except UnicodeErro...
wikipedia.output(u'You did not give me anything to do, quitting.')
wikipedia.showHelp('image')
def main(): oldImage = None newImage = None summary = '' always = False # read command line parameters for arg in wikipedia.handleArgs(): if arg == '-always': always = True elif arg.startswith('-summary'): if len(arg) == len('-summary'): summary = wikipedia.input(u'Choose an edit summary: ') else: summary = arg[len('-s...
'is': u'Kerfissíður',
'is': u'Kerfissíða',
def __init__(self):
pl = wikipedia.PageLink(wikipedia.mylang, listpage)
try: pl = wikipedia.PageLink(wikipedia.mylang, listpage) except NoPage: print 'The page ' + listpage + ' could not be loaded from the server.' sys.exit()
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...