rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
start = hit + '!'
start = Page(self,hit).titleWithoutNamespace() + '!'
def allpages(self, start = '!', namespace = 0, throttle = True): """Generator which yields all articles in the home language in alphanumerical order, starting at a given page. By default, it starts at '!', so it should yield all pages.
def ignoredBecauseOfContents(self, text):
def checkContents(self, text): ''' For a given text, returns False if none of the regular expressions given in the dictionary at the top of this class matches a substring of the text. Otherwise returns the substring which is matched by one of the regular expressions. '''
def ignoredBecauseOfContents(self, text): for ig in self.ignore_contents_regexes: match = ig.search(text) if match: return match.group() return False
return False
return None
def ignoredBecauseOfContents(self, text): for ig in self.ignore_contents_regexes: match = ig.search(text) if match: return match.group() return False
ignoreReason = self.ignoredBecauseOfContents(text)
ignoreReason = self.checkContents(text)
def treat(self, refpl, disambPl): """ Parameters: disambPl - The disambiguation page or redirect we don't want anything to link on refpl - A page linking to disambPl Returns False if the user pressed q to completely quit the program. Otherwise, returns True. """ if self.mylang in link_trail: linktrail=link_trail[self.m...
if ignore.has_key(self.mylang): ignore[self.mylang] += self.mysite.namespaces()
if ignore_title.has_key(self.mylang): ignore_title[self.mylang] += self.mysite.namespaces()
def run(self): if self.main_only: if ignore.has_key(self.mylang): ignore[self.mylang] += self.mysite.namespaces() else: ignore[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.setAction(wikipedi...
ignore[self.mylang] = self.mysite.namespaces()
ignore_title[self.mylang] = self.mysite.namespaces()
def run(self): if self.main_only: if ignore.has_key(self.mylang): ignore[self.mylang] += self.mysite.namespaces() else: ignore[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.setAction(wikipedi...
ns = wikipedia.family.category_namespaces(wikipedia.mylang)
def articles(self, recurse = 0): ns = wikipedia.family.category_namespaces(wikipedia.mylang) articles = [] titles = self.catlist(recurse) for title in titles: for ins in ns: # if the current link points to a subcategory if title.startswith(ins + ':'): # don't return this link titles.remove(title) for title in titles: n...
for ins in ns:
is_category = False for namespace in wikipedia.family.category_namespaces(wikipedia.mylang):
def articles(self, recurse = 0): ns = wikipedia.family.category_namespaces(wikipedia.mylang) articles = [] titles = self.catlist(recurse) for title in titles: for ins in ns: # if the current link points to a subcategory if title.startswith(ins + ':'): # don't return this link titles.remove(title) for title in titles: n...
if title.startswith(ins + ':'): titles.remove(title) for title in titles: npage = wikipedia.PageLink(self.code(), title) articles.append(npage)
if title.startswith(namespace + ':'): is_category = True if not is_category: npage = wikipedia.PageLink(self.code(), title) articles.append(npage)
def articles(self, recurse = 0): ns = wikipedia.family.category_namespaces(wikipedia.mylang) articles = [] titles = self.catlist(recurse) for title in titles: for ins in ns: # if the current link points to a subcategory if title.startswith(ins + ':'): # don't return this link titles.remove(title) for title in titles: n...
print ' ? - Read the page'
print ' ? - Print first part of the page (longer and longer)'
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...
length = 1000
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...
print '' full_text = article.get() print '' wikipedia.output(full_text[0:length])
contextLength += 500 print wikipedia.output(full_text[:contextLength]) print
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...
if len(full_text) > length:
if len(full_text) > contextLength:
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...
length = length+500
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...
fn = fn.encode(wikipedia.code2encoding(wikipedia.mylang))
else: fn = unicode(fn, config.console_encoding) try: fn = fn.encode(wikipedia.code2encoding(wikipedia.mylang)) except UnicodeDecodeError: print "This filename can't be displayed in " + wikipedia.code2encoding(wikipedia.mylang) sys.exit(1)
def get_image(fn, target, description, debug=False): # 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 = r...
urlR = re.compile(r'<div class="fullImageLink" id="file"><a href="(?P<url1>.+?)">|<div class="fullImageLink" id="file"><img border="0" src="(?P<url2>.+?)"')
urlR = re.compile(r'<div class="fullImageLink" id="file">.+?\n.*?<a href="(?P<url>.+?)"', re.DOTALL)
def fileUrl(self): urlR = re.compile(r'<div class="fullImageLink" id="file"><a href="(?P<url1>.+?)">|<div class="fullImageLink" id="file"><img border="0" src="(?P<url2>.+?)"') m = urlR.search(self.getImagePageContents()) try: url = m.group('url1') or m.group('url2') except AttributeError: raise NoPage(u'Image page %s n...
url = m.group('url1') or m.group('url2')
url = m.group('url')
def fileUrl(self): urlR = re.compile(r'<div class="fullImageLink" id="file"><a href="(?P<url1>.+?)">|<div class="fullImageLink" id="file"><img border="0" src="(?P<url2>.+?)"') m = urlR.search(self.getImagePageContents()) try: url = m.group('url1') or m.group('url2') except AttributeError: raise NoPage(u'Image page %s n...
path = site.family.version_history_address(site, self.urlname())
path = site.family.version_history_address(self.site().language(), self.urlname()) print path
def getVersionHistory(self, forceReload = False): """ Loads the version history page and returns a list of tuples, where each tuple represents one edit and is built of edit date/time, user name, and edit summary. """ site = self.site() path = site.family.version_history_address(site, self.urlname())
print edits
def getVersionHistory(self, forceReload = False): """ Loads the version history page and returns a list of tuples, where each tuple represents one edit and is built of edit date/time, user name, and edit summary. """ site = self.site() path = site.family.version_history_address(site, self.urlname())
sourceImagePage.put(description + '\n\n' + nowCommonsTemplate[sourceSite.lang] % targetFilename, comment = nowCommonsMessage[sourceSite.lang])
sourceImagePage.put(sourceImagePage.get() + '\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 ...
print "WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),arg)
pl3 = wikipedia.PageLink(wikipedia.mylang,arg.args[0]) print "WARNING: %s is redirect to [[%s]]. Ignoring."%(pl2.aslocallink(),pl3.aslocallink())
def main(): import re 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 fir...
rBody = re.compile('.*<div id\=\"bodyContent\">.*')
rBody = re.compile('.*<div id\=\"content\">.*')
def extractArticle(data): """ takes a string with the complete HTML-file and returns the article which is contained in <div id='article'> and the pagestats which contain information on last change """ images = [] s = StringIO.StringIO(data) rPagestats = re.compile('.*(\<span id\=(\"|\')pagestats(\"|\')\>.*\<\/span\>)...
divLevel = 0
divLevel = 1
def extractArticle(data): """ takes a string with the complete HTML-file and returns the article which is contained in <div id='article'> and the pagestats which contain information on last change """ images = [] s = StringIO.StringIO(data) rPagestats = re.compile('.*(\<span id\=(\"|\')pagestats(\"|\')\>.*\<\/span\>)...
divLast = divLevel-1
divLast = divLevel-2
def extractArticle(data): """ takes a string with the complete HTML-file and returns the article which is contained in <div id='article'> and the pagestats which contain information on last change """ images = [] s = StringIO.StringIO(data) rPagestats = re.compile('.*(\<span id\=(\"|\')pagestats(\"|\')\>.*\<\/span\>)...
rImage = re.compile('.*?<a href=\"\/wiki\/[^:]*:([^"]*)" class="image"') rThumb = re.compile('.*?<div class="magnify"[^>]*?><a href="\/wiki\/[^:]*?:([^"]*)"')
rImage = re.compile('.*<a href="/wiki/.*?:(.*?)".*?[\n]*?.*?class="internal"') rThumb = re.compile('.*<a href="/wiki/.*?:(.*?)".*?class="image"') last = ""
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\/[^:]*:([^"]*)" class="image"') rThu...
path = md5.new(img.group(1)).hexdigest() images.append( {'image':img.group(1), 'path': str(path[0])+"/"+str(path[0:2])+"/"}) img = True
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
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\/[^:]*:([^"]*)" class="image"') rThu...
img = False
pass
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\/[^:]*:([^"]*)" class="image"') rThu...
try: path = md5.new(img.group(1)).hexdigest() images.append( {'image':img.group(1), 'path': str(path[0])+"/"+str(path[0:2])+"/"})
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
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\/[^:]*:([^"]*)" class="image"') rThu...
img = False
pass images.sort()
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\/[^:]*:([^"]*)" class="image"') rThu...
for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl)
f=open(arg[6:], 'r') R=re.compile(r'.*\[\[([^\]]*)\]\].*') m = False for line in f.readlines(): m=R.match(line) if m: sa.append(string.replace(m.group(1), " ", "_")) else: print "ERROR: Did not understand %s line:\n%s" % ( arg[6:], repr(line)) f.close()
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:"): for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl) elif arg.start...
sa.append(arg)
sa.append(arg.replace(" ", "_"))
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:"): for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl) elif arg.start...
print " done"
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:"): for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl) elif arg.start...
if os.path.isfile(output_directory + article + ".txt") and overwrite_articles == False:
filename = article.replace("/", "_") if os.path.isfile(output_directory + filename + ".txt") and overwrite_articles == False:
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:"): for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl) elif arg.start...
f = open (output_directory + article + ".txt", 'w')
f = open (output_directory + filename + ".txt", 'w')
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:"): for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl) elif arg.start...
print 'done'
print "\t\t", (len(content)/1024), "KB done"
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:"): for pl in wikipedia.PageLinksFromFile(arg[6:]): sa.append(pl) elif arg.start...
getalternatives = False
getAlternatives = False
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 ...
def replaceLinks(self, pl, new, bot):
def replaceLinks(self, pl, newPages, bot):
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
wikipedia.output(u"BUG: %s is not in the list of new links!" % pl.aslink(forceInterwiki = True))
wikipedia.output(u"BUG>>> %s is not in the list of new links!" % pl.aslink(forceInterwiki = True))
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
old={} try: for pl2 in pl.interwiki(): old[pl2.site()] = pl2 except wikipedia.NoPage: wikipedia.output(u"BUG: %s no longer exists?" % pl.aslink(forceInterwiki = True)) return False
for pl2 in pl.interwiki(): old[pl2.site()] = pl2 except wikipedia.NoPage: wikipedia.output(u"BUG>>> %s no longer exists?" % pl.aslink(forceInterwiki = True)) return False mods, removing = compareLanguages(old, new, insite = pl.site()) if globalvar.autonomous and not globalvar.force and len(removing) > 0: for site i...
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
if not mods and not globalvar.always: wikipedia.output(u'No changes needed' ) else: if mods: wikipedia.output(u"Changes to be made: %s" % mods) oldtext = pl.get() newtext = wikipedia.replaceLanguageLinks(oldtext, new, site = pl.site()) if globalvar.debug: wikipedia.showDiff(oldtext, newtext) if newtext != oldtext:
if not mods and not globalvar.always: wikipedia.output(u'No changes needed' ) else: if mods: wikipedia.output(u"Changes to be made: %s" % mods) oldtext = pl.get() newtext = wikipedia.replaceLanguageLinks(oldtext, new, site = pl.site()) if globalvar.debug: wikipedia.showDiff(oldtext, newtext) if newtext != oldtext: as...
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
if removing: self.problem('Found incorrect link to %s in %s'% (",".join([x.lang for x in removing]), pl.aslink(forceInterwiki = True))) 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']) else: answer = 'y' if answer == 'y': if bot: while wikipedia.get_throttle.waittime() + 2.0 < wikipedia.put_throttle.waittime(): print "NOTE: Performing a recur...
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
answer = wikipedia.inputChoice(u'Submit?', ['Yes', 'No'], ['y', 'n'])
break if str(status) == '302': return True
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
answer = 'y' if answer == 'y': if bot: while wikipedia.get_throttle.waittime() + 2.0 < wikipedia.put_throttle.waittime(): print "NOTE: Performing a recursive query first to save time...." qdone = bot.oneQuery() if not qdone: break print "NOTE: Updating live wiki..." timeout=60 while 1: try: status, reason, data = p...
print status, reason else: raise LinkMustBeRemoved('Found incorrect link to %s in %s'% (",".join([x.lang for x in removing]), pl.aslink(forceInterwiki = True))) return False
def replaceLinks(self, pl, new, bot): """ Returns True if saving was successful. """ if globalvar.localonly: # In this case only continue on the Page we started with if pl != self.pl(): return False
if first in self.validLanguageLinks() or (first in self.validLanguageLinks() and self.family.known_families[first] != self.family.name):
if first in self.validLanguageLinks() or (first in self.family.known_families and self.family.known_families[first] != self.family.name):
def isInterwikiLink(self, s): """ 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 first, rest = s.split(':',1) # interwiki codes are case-insensitive first = first.lower() if first in se...
self._site = getSite(lowerNs)
self._site = getSite(lowerNs, self.site().family.name)
def __init__(self, site, title, insite = None, tosite = None, defaultNamespace = 0): """ Constructor. Normally called with two arguments: Parameters: 1) The wikimedia site on which the page resides 2) The title of the page as a unicode string
return self.langs[code]
return 'dvd.wikidev.net'
def hostname(self, code): return self.langs[code]
wikipedia.output(__doc__, 'utf-8')
wikipedia.showHelp('redirect')
def main(): # read command line parameters # what the bot should do (either resolve double redirs, or delete broken redirs) action = None # where the bot should get his infos from (either None to load the maintenance # special page from the live wiki, or the filename of a local XML dump file) xmlFilename = None # Which...
self.moveCatPage = True
self.moveCatPage = moveCatPage
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...
inname = wikipedia.input(u'Which page to check: ') inname = unicode(inname, config.console_encoding) inname = inname.encode(wikipedia.myencoding())
inname = wikipedia.input(u'Which page to check: ', wikipedia.myencoding())
def ReadWarnfile(fn, sa): import re R=re.compile(r'WARNING: ([^\[]*):\[\[([^\[]+)\]\]([^\[]+)\[\[([^\[]+):([^\[]+)\]\]') f=open(fn) hints={} for line in f.readlines(): m=R.search(line) if m: #print "DBG>",line if m.group(1)==wikipedia.mylang: #print m.group(1), m.group(2), m.group(3), m.group(4), m.group(5) if not hint...
text = getPage(mylang, family.allpagesname(mylang, start), do_quote=0, do_edit=0)
returned_html = getPage(mylang, family.allpagesname(mylang, start), do_quote=0, do_edit=0) try: ibegin = returned_html.index('<!-- start content -->') iend = returned_html.index('<!-- end content -->') except ValueError: raise NoPage('Couldn\'t extract allpages special page') returned_html = returned_html[ibegin:iend...
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...
R = re.compile('title =\"(.*?)\"')
R = re.compile('title ="(.*?)"')
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...
for hit in R.findall(text): if not ':' in hit: if not hit in ['Hoofdpagina','In_het_nieuws']: n = n + 1 if family.version(mylang)=="1.2": yield PageLink(mylang, url2link(hit, code = mylang, incode = mylang)) else: yield PageLink(mylang, hit) start = hit + '%20%200'
for hit in R.findall(returned_html): n = n + 1 if family.version(mylang)=="1.2": yield PageLink(mylang, url2link(hit, code = mylang, incode = mylang)) else: yield PageLink(mylang, hit) start = hit + '%20%200'
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...
choice2 = wikipedia.input(u'Do you want to make redirect %s point to %s? [y|N]' % (refpl.linkname(), target)) if choice2 == 'y': redir_text = ' refpl.put(redir_text)
if solve_redirect: choice2 = wikipedia.input(u'Do you want to make redirect %s point to %s? [y|N]' % (refpl.linkname(), target)) if choice2 == 'y': redir_text = ' refpl.put(redir_text)
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)...
result.append(page)
if not isInterwikiLink(page.title()): result.append(page)
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())
print data
def getData(self): if not self.pages: return addr = 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 = u'\r...
dict,val = getDictionaryYear( wikipedia.mylang, s )
dict,val = date.getDictionaryYear( wikipedia.getSite().language(), s )
def isdate(s): """returns true iff s is a date or year """ dict,val = getDictionaryYear( wikipedia.mylang, s ) return dict != None
page=wikipedia.Page(wikipedia.mylang,pagetitle)
page=wikipedia.Page(wikipedia.getSite(),pagetitle)
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...
pl2=wikipedia.Page(mysite,pl.getRedirectTarget()) checkprepare(pl2)
include(pl,realinclude=False)
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 globalvar.autonomous: while 1: if globalvar.bell: sys.stdout.write('\07') answer = raw_input("Use (f)ormer or (l)atter or (n)either or (g)ive up?") if answer.startswith('f'): break elif answer.startswith('l'): new[pl.code()] = pl break elif answer.startswith('n'): new[pl.code()] = None break elif answer.startswi...
if globalvar.autonomous: return while 1: if globalvar.bell: sys.stdout.write('\07') answer = raw_input("Use (f)ormer or (l)atter or (n)either or (g)ive up?") if answer.startswith('f'): break elif answer.startswith('l'): new[pl.code()] = pl break elif answer.startswith('n'): new[pl.code()] = None break elif answer.start...
def finish(self): """Round up the subject, making any necessary changes. This method should be called exactly once after the todo list has gone empty.""" if self.inpl.isRedirectPage(): return if not self.isDone(): raise "Bugcheck: finish called before done" print "======Post-processing %s======"%(self.inpl.asasciilink(...
print "WARNING: No text area found on %s%s. Maybe the server is down. Retrying in %d minutes..." % (host, address, retry_idle_time)
print "WARNING: No text area found on %s%s. Maybe the server is down. Retrying in %i minutes..." % (site.hostname(), path, retry_idle_time)
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...
lineCount = int(self.logBox.index(END).split('.')[0]) - 1
lineCount = float(self.logBox.index(END).split('.')[0]) - 1
def output(self, text, urgency = 1, colors = None, newline = True): """ urgency levels: 0 - Debug output. Won't be shown in normal mode. 1 - Will be shown in log window. 2 - Will be shown in error box.
self.foundin[page2] = pl
self.foundin[page2] = [pl]
def workDone(self, counter): """This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo.""" # Loop over all the pages that should have been taken care of ...
if page.exists and not not page.isDisambig():
if page.exists and not page.isDisambig():
def getFoundNonDisambig(self,site): """ If we found a non-disambiguation on the given site while working on the subject, this method returns it. If several ones have been found, the first one will be returned. Otherwise, None will be returned. """ for page in self.done + self.pending: if page.site() == site: if page.ex...
page = location.group()
contents = location.group()
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) except AttributeError: wikipedia.output(u"No title found - skipping a page.") else: pl = wikipe...
page = location.group(1)
contents = location.group(1)
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) except AttributeError: wikipedia.output(u"No title found - skipping a page.") else: pl = wikipe...
title = re.search("'''(.*?)'''",page).group(1)
title = re.search("'''(.*?)'''", contents).group(1)
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) except AttributeError: wikipedia.output(u"No title found - skipping a page.") else: pl = wikipe...
pl = wikipedia.Page(mysite,wikipedia.UnicodeToAsciiHtml(title)) wikipedia.output(pl.title()) if pl.exists():
page = wikipedia.Page(mysite, title) wikipedia.output(page.title()) if page.exists():
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) except AttributeError: wikipedia.output(u"No title found - skipping a page.") else: pl = wikipe...
pl.put(page, comment = commenttext, minorEdit = False)
page.put(contents, comment = commenttext, minorEdit = False)
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) except AttributeError: wikipedia.output(u"No title found - skipping a page.") else: pl = wikipe...
if utf: f=codecs.open(filename,'rb',encoding='utf-8') else: f=open(filename,'r') for line in f.readlines(): text.append(line) text=''.join(text)
f = codecs.open(filename,'r', encoding = config.textfile_encoding) text = f.read()
def main(): text = [] if utf: f=codecs.open(filename,'rb',encoding='utf-8') else: f=open(filename,'r') for line in f.readlines(): text.append(line) text=''.join(text) findpage(text)
elif arg=="-utf": import codecs utf = True elif arg=="-log": import logger sys.stdout = logger.Logger(sys.stdout, filename = 'pagefromfile.log')
def main(): text = [] if utf: f=codecs.open(filename,'rb',encoding='utf-8') else: f=open(filename,'r') for line in f.readlines(): text.append(line) text=''.join(text) findpage(text)
'lt': u'Vikišaltiniai' 'no': u'Wikikilden'
'lt': u'Vikišaltiniai', 'no': u'Wikikilden',
def __init__(self): family.Family.__init__(self) self.name = 'wikisource' for lang in self.knownlanguages: self.langs[lang] = lang+'.wikisource.org'
print "ERROR: couldn't find " + page_title
wikipedia.output(u"ERROR: couldn't find %s" % pl.linkname())
def treat(self, pl): ''' Loads a page, converts all HTML tables in its text to wiki syntax, and saves the converted text. Returns True if the converted table was successfully saved, otherwise returns False. ''' site = pl.site() try: text = pl.get() except wikipedia.NoPage: print "ERROR: couldn't find " + page_title ret...
wikipedia.output(u'Skipping locked page %s' % page_title)
wikipedia.output(u'Skipping locked page %s' % pl.linkname())
def treat(self, pl): ''' Loads a page, converts all HTML tables in its text to wiki syntax, and saves the converted text. Returns True if the converted table was successfully saved, otherwise returns False. ''' site = pl.site() try: text = pl.get() except wikipedia.NoPage: print "ERROR: couldn't find " + page_title ret...
wikipedia.output(u'Skipping redirect %s' % page_title)
wikipedia.output(u'Skipping redirect %s' % pl.linkname())
def treat(self, pl): ''' Loads a page, converts all HTML tables in its text to wiki syntax, and saves the converted text. Returns True if the converted table was successfully saved, otherwise returns False. ''' site = pl.site() try: text = pl.get() except wikipedia.NoPage: print "ERROR: couldn't find " + page_title ret...
wikipedia.setAction(msg[msglang]+wrd)
wikipedia.setAction(msg[msglang]+': '+wrd)
def getReferences(pl): x = wikipedia.getReferences(pl) # Remove ignorables if ignore.has_key(pl.code()): ig=ignore[pl.code()] for i in range(len(x)-1, -1, -1): if x[i] in ig: del x[i] return x
+ "\s*<a href=.+?>.+?<\/a><br \/>\n" + "\s*.*?<a href=.+?>.+?<\/a>\n"
+ "\s*<a href=.+?>(.+?)<\/a><br \/>\n" + "\s*<a href=.+?>.+?<\/a>\n"
def refresh_messages(lang): host = wikipedia.family.hostname(lang) # get 'all messages' special page's URL url = wikipedia.family.allmessages_address(lang) print 'Retrieving MediaWiki messages for %s' % lang allmessages, charset = wikipedia.getUrl(host,url) print 'Parsing MediaWiki messages' # First group is MediaWiki...
+ "\s*.+?\n"
+ "\s*(.+?)\n"
def refresh_messages(lang): host = wikipedia.family.hostname(lang) # get 'all messages' special page's URL url = wikipedia.family.allmessages_address(lang) print 'Retrieving MediaWiki messages for %s' % lang allmessages, charset = wikipedia.getUrl(host,url) print 'Parsing MediaWiki messages' # First group is MediaWiki...
regex = fix['exceptions']
exceptions = fix['exceptions']
def generator(source, replacements, exceptions, regex, textfilename = None, sqlfilename = None, pagename = None): if source == 'sqldump': for pl in read_pages_from_sql_dump(sqlfilename, replacements, exceptions, regex): yield pl elif source == 'textfile': for pl in read_pages_from_text_file(textfilename): yield pl elif...
title = title.split(':')
title = link2url(title, site = self._site, insite = insite) title = title.split('%3A')
def __init__(self, site, title = None, insite = None, tosite = None): """ Constructor. Normally called with two arguments: Parameters: 1) The wikimedia site on which the page resides 2) The title of the page as a unicode string The argument insite can be specified to help decode the name; it is the wikimedia site wher...
title = ':'.join(title) self._urlname = link2url(title, site = self._site, insite = insite)
title[0] = link2url (title[0], site = self._site, insite = insite) title = '%3A'.join(title) self._urlname = title
def __init__(self, site, title = None, insite = None, tosite = None): """ Constructor. Normally called with two arguments: Parameters: 1) The wikimedia site on which the page resides 2) The title of the page as a unicode string The argument insite can be specified to help decode the name; it is the wikimedia site wher...
self.foundin = {self.inpl:[]}
def __init__(self, pl, hints = None): """Constructor. Takes as arguments the PageLink on the home wikipedia plus optionally a list of hints for translation""" # Remember the "origin page" self.inpl = pl # Mark the origin page as todo. self.todo = {pl:pl.code()} # Nothing has been done yet self.done = {} # Add the trans...
def conditionalAdd(self, pl, counter):
def conditionalAdd(self, pl, counter, foundin):
def conditionalAdd(self, pl, counter): """Add the pagelink given to the todo list, but only if we didn't know it before. If it is added, update the counter accordingly.""" if (pl not in self.done and pl not in self.todo and pl not in self.pending): self.todo[pl] = pl.code() counter.plus(pl.code()) #print "DBG> Found ne...
if (pl not in self.done and pl not in self.todo and pl not in self.pending):
if self.foundin.has_key(pl): self.foundin[pl].append(foundin) return False else: self.foundin[pl]=[foundin]
def conditionalAdd(self, pl, counter): """Add the pagelink given to the todo list, but only if we didn't know it before. If it is added, update the counter accordingly.""" if (pl not in self.done and pl not in self.todo and pl not in self.pending): self.todo[pl] = pl.code() counter.plus(pl.code()) #print "DBG> Found ne...
return False
def conditionalAdd(self, pl, counter): """Add the pagelink given to the todo list, but only if we didn't know it before. If it is added, update the counter accordingly.""" if (pl not in self.done and pl not in self.todo and pl not in self.pending): self.todo[pl] = pl.code() counter.plus(pl.code()) #print "DBG> Found ne...
if self.conditionalAdd(pl3, counter):
if self.conditionalAdd(pl3, counter, pl):
def workDone(self, counter): """This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo.""" # Loop over all the pages that should have been taken care of ...
if self.conditionalAdd(pl2, counter):
if self.conditionalAdd(pl2, counter, pl):
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 ...
def assemblefirstrun(self): temp = {}
def assemble(self):
def assemblefirstrun(self): temp = {} 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: err = 'Someone refers to %s with us' % pl.asasciilink() self.problem(err) if globalvar.autonomous: return None eli...
err = 'Someone refers to %s with us' % pl.asasciilink() self.problem(err) if globalvar.autonomous:
self.problem("Found link to %s"%pl.asasciilink()) for pl2 in self.foundin[pl]: print " ",pl2.asasciilink() nerr += 1 elif pl.exists() and not pl.isRedirectPage(): if code in new: new[code].append(pl) else: new[code] = [pl] if 'zh-cn' in new or 'zh-tw' in new: if 'zh' in new: del new[zh] print "Ignoring links to zh i...
def assemblefirstrun(self): temp = {} 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: err = 'Someone refers to %s with us' % pl.asasciilink() self.problem(err) if globalvar.autonomous: return None eli...
elif pl.exists() and not pl.isRedirectPage(): if new.has_key(code) and new[code] is None: print "NOTE: Ignoring %s"%(pl.asasciilink()) elif temp.has_key(code) and temp[code] is None: if globalvar.autonomous: return None answer = ' ' while answer not in 'yng': answer = raw_input('%s y(es)/n(o)/g(ive up)? '%pl.asasciilin...
answer = int(answer) result[k] = v[answer-1] else: result[k] = v[0] if globalvar.autonomous and nerr>0: return None return result
def assemblefirstrun(self): temp = {} 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: err = 'Someone refers to %s with us' % pl.asasciilink() self.problem(err) if globalvar.autonomous: return None eli...
if globalvar.autonomous: new = self.assemblefirstrun() if new == None: return else: new = self.assemblesecondrun(new) else: new = self.assemblefirstrun() if new == None: return new = self.assemblesecondrun(new, self.problemfound) if new == None: return
new = self.assemble() if new == None: return
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.
choice = wikipedia.inputChoice(u'What shall be done with this selflink?', ['unlink', 'make bold', 'skip'], ['U', 'b', 's'], 'u')
choice = wikipedia.inputChoice(u'What shall be done with this selflink?', ['unlink', 'make bold', 'skip', 'context?'], ['U', 'b', 's', '?'], 'u')
def run(self): linktrail = wikipedia.getSite().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 label is the alte...
langlist += language
langlist += [language]
def validLanguageLinks(self): langlist = [] for language in self.languages(): if not language in self.namespaces(): langlist += language return langlist
raise
pass
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, get_redirect = True, ...
answer = self.ask(askit,pl)
def assemblefirstrun(self): temp = {} 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: err = 'Someone refers to %s with us' % pl.asasciilink() self.problem(err) if globalvar.autonomous: return None eli...
x = wikipedia.getReferences(pl, follow_redirects = False) print "Found %d references" % len(x)
refs = wikipedia.getReferences(pl, follow_redirects = False) print "Found %d references" % len(refs)
def getReferences(pl): x = wikipedia.getReferences(pl, follow_redirects = False) print "Found %d references" % len(x) # Remove ignorables if ignore.has_key(pl.code()): ignore_regexes =[] for ig in ignore[pl.code()]: ignore_regexes.append(re.compile(ig)) for Rignore in ignore_regexes: for i in range(len(x)-1, -1, -1): i...
for i in range(len(x)-1, -1, -1): if Rignore.match(x[i]): wikipedia.output('Ignoring page ' + x[i], wikipedia.myencoding()) del x[i] return x
for i in range(len(refs)-1, -1, -1): if Rignore.match(refs[i]): wikipedia.output('Ignoring page ' + refs[i], wikipedia.myencoding()) del refs[i] return refs
def getReferences(pl): x = wikipedia.getReferences(pl, follow_redirects = False) print "Found %d references" % len(x) # Remove ignorables if ignore.has_key(pl.code()): ignore_regexes =[] for ig in ignore[pl.code()]: ignore_regexes.append(re.compile(ig)) for Rignore in ignore_regexes: for i in range(len(x)-1, -1, -1): i...
titleWithSection = titleWithSection.replace('_', ' ')
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:
output(u'Getting %s...' % path)
output(u'Getting http://%s%s' % (self.site().hostname(), path))
def getImagePageContents(self): if not self._imagePageContents: path = self.site().get_address(self.urlname()) output(u'Getting %s...' % path) self._imagePageContents = self.site().getUrl(path) return self._imagePageContents
url = m.group('url1') or m.group('url2') print url
try: url = m.group('url1') or m.group('url2') except AttributeError: print self.getImagePageContents() raise NoPage(u'Image page %s not found.' % self.title())
def fileUrl(self): urlR = re.compile(r'<div class="fullImageLink" id="file"><a href="(?P<url1>.+?)">|<div class="fullImageLink" id="file"><img border="0" src="(?P<url2>.+?)"') m = urlR.search(self.getImagePageContents()) url = m.group('url1') or m.group('url2') print url return url #filename = self.titleWithoutNamespac...
def isOnCommons(self):
def fileIsOnCommons(self):
def isOnCommons(self): return self.fileUrl().startswith(u'http://upload.wikimedia.org/wikipedia/commons/')