rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
choice = wikipedia.input('WARNING: %s doesn\'t seem to be a disambiguation page, but %s is one. Follow it anyway? [y|N]' % (self.inpl.aslink(), pl.aslink()))
choice = wikipedia.inputChoice('WARNING: %s doesn\'t seem to be a disambiguation page, but %s is one. Follow it anyway?' % (self.inpl.aslink(), pl.aslink()), ['Yes', 'No'], ['y', 'N'], 'N')
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 ...
choice = wikipedia.input('WARNING: %s is in namespace %i, but %s is in namespace %i. Follow it anyway? [y|N]' % (self.inpl.aslink(), self.inpl.namespace(), page2.aslink(), page2.namespace()))
choice = wikipedia.inputChoice('WARNING: %s is in namespace %i, but %s is in namespace %i. Follow it anyway?' % (self.inpl.aslink(), self.inpl.namespace(), page2.aslink(), page2.namespace()), ['Yes', 'No'], ['y', 'N'], 'N')
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 ...
answer = wikipedia.input(u"What should be done [(a)ccept, (r)eject, (g)ive up, accept a(l)l] :")
answer = wikipedia.inputChoice(u'What should be done?', ['accept', 'reject', 'give up', 'accept all'], ['a', 'r', 'G', 'l'], 'G')
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...
answer = wikipedia.input(u'Submit? [y|N]')
answer = wikipedia.inputChoice(u'Submit?', ['Yes', 'No'], ['y', 'N'], 'N')
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.
start = wikipedia.input(u'Which page to start from: ', wikipedia.myencoding())
start = wikipedia.input(u'Which page to start from: ')
def readWarnfile(filename, sa): import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints (hints, removeHints) = reader.getHints() for pagename in hints.iterkeys(): pl = wikipedia.Page(wikipedia.getSite(), pagename) # The WarnfileReader gives us a list of pagelinks, but titletranslate.py exp...
inname = wikipedia.input(u'Which page to check: ', wikipedia.myencoding())
inname = wikipedia.input(u'Which page to check: ')
def readWarnfile(filename, sa): import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints (hints, removeHints) = reader.getHints() for pagename in hints.iterkeys(): pl = wikipedia.Page(wikipedia.getSite(), pagename) # The WarnfileReader gives us a list of pagelinks, but titletranslate.py exp...
print repr(s),repr(s2[:100])
def treesearch(pl): arr = {pl:None} # First make one step based on the language itself try: n = treestep(arr, pl, abort_on_redirect = 1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n == 0 and not arr[pl]: print "Mother doesn't exist" return if untranslated: if len(arr) > 1: print "Already has tr...
'ru' : [u'disambig'],
'ru' : [u'disambig',u'значения'],
def __init__(self):
namespaces.append(namespace_title.lower())
if namespace_title != namespace_title.lower(): namespaces.append(namespace_title.lower())
def category_namespaces(self, code): namespaces = [] namespace_title = self.namespace(code, 14) namespaces.append(namespace_title) namespaces.append(namespace_title.lower()) default_namespace_title = self.namespace('_default', 14) if namespace_title != default_namespace_title: namespaces.append(default_namespace_title)...
namespaces.append(default_namespace_title.lower())
if default_namespace_title != default_namespace_title.lower(): namespaces.append(default_namespace_title.lower())
def category_namespaces(self, code): namespaces = [] namespace_title = self.namespace(code, 14) namespaces.append(namespace_title) namespaces.append(namespace_title.lower()) default_namespace_title = self.namespace('_default', 14) if namespace_title != default_namespace_title: namespaces.append(default_namespace_title)...
for original_cat in article.categories(): wikipedia.output('* %s' % original_cat.linkname())
for cat in article.categories(): wikipedia.output('* %s' % cat.linkname())
def move_to_category(article, original_cat, current_cat): print wikipedia.output(u'Treating page %s, currently in category %s' % (article.linkname(), current_cat.linkname())) subcatlist = get_subcats(current_cat) supercatlist = get_supercats(current_cat) print if len(subcatlist) == 0: print 'This category has no subcat...
except UnicodeEncodeError, arg: return False, u'Non-ASCII Characters in URL: %s' % arg
def check(self, useHEAD = True): """ Returns True and the server status message if the page is alive. Otherwise returns false """ try: wasRedirected = self.resolveRedirect(useHEAD = useHEAD) except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % ar...
notInside = '\]\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...
linkR = re.compile(r'http[s]?://[^\]\s<>}"]*?[^\]\s\)\.:;,<>}\|"](?=\'\')|http[s]?://[^\]\s<>}"]*[^\]\s\)\.:;,<>}"\|]')
linkR = re.compile(r'http[s]?://[^' + notInside + ']*?[^' + notAtEnd + '](?=[' + notAtEnd+ ']*\'\')|http[s]?://[^' + notInside + ']*[^' + notAtEnd + ']')
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...
elif not xpl in shouldlink:
if not xpl in shouldlink:
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" for site in new.keys(): pl = new[site] if not unequal.bigger(self.inpl, pl) and not pl.hashname(): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl...
'af': u'%d v.Chr.',
'af':u'%d v.C.',
def __call__(self, m, d): import wikipedia return wikipedia.html2unicode((date_format[m][self.site.lang]) % d, site = self.site)
'he': u'%d &
'he':u'%d לפנה"ס',
def __call__(self, m, d): import wikipedia return wikipedia.html2unicode((date_format[m][self.site.lang]) % d, site = self.site)
'ja':'%d& 'zh':'%d& 'ko':'%d& 'minnan':'%d n&icirc;', 'ur':'%d&
'ja':u'%d年', 'zh':u'%d年', 'ko':u'%d년', 'minnan':u'%d nî', 'ur':u'%dسبم'
def __call__(self, m, d): import wikipedia return wikipedia.html2unicode((date_format[m][self.site.lang]) % d, site = self.site)
self.todo = []
self.todo = {}
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 globalvar.bell: sys.stdout.write('\07')
def assemble(self, returnonquestion = False, askall = False): if globalvar.bell: sys.stdout.write('\07') new = {} for pl in self.done.keys(): code = pl.code() if code == wikipedia.mylang and pl.exists() and not pl.isRedirectPage() and not pl.isEmpty(): if pl != self.inpl: if returnonquestion: return None self.problem('...
newfn = wikipedia.input(u'Better name:')
while True: newfn = wikipedia.input(u'Better name:') if '/' in newfn: print "Invalid character: '/'. Please try again" else: break
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
print wikipedia.output(description)
wikipedia.output(description)
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
formdata = {} formdata["wpUploadDescription"] = description if wikipedia.version() >= '1.4': formdata["wpUploadCopyStatus"] = wikipedia.input(u"Copyright status: ") formdata["wpUploadSource"] = wikipedia.input(u"Source of image: ") else: formdata["wpUploadAffirm"] = "1" formdata["wpUpload"] = "upload bestand" formdata[...
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
try: description = description.encode(wikipedia.myencoding()) except UnicodeEncodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) except UnicodeDecodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding())
for key in formdata: assert isinstance(key, basestring), "ERROR: %s is not a string but %s" % (key, type(key)) try: formdata[key] = formdata[key].encode(wikipedia.myencoding()) except (UnicodeEncodeError, UnicodeDecodeError): formdata[key] = wikipedia.UnicodeToAsciiHtml(formdata[key]).encode(wikipedia.myencoding())
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
(('wpUploadDescription', description), ('wpUploadAffirm', '1'), ('wpIgnoreWarning', '1'), ('wpUpload','upload bestand')),
formdata.items(),
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = fi...
print repr(data)
def getData(self): import httplib try: addr = self.addr%special[self.code] except KeyError: print "BUG: Can not find name of Special in %s:" % self.code raise pagenames = u'\r\n'.join([x.hashfreeLinkname() for x in self.pages]) pagenames = forCode(pagenames, self.code) data = urlencode(( ('action', 'submit'), ('pages',...
def check(self):
def check(self, useHEAD = True):
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false """ try: wasRedirected = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg:...
wasRedirected = self.resolveRedirect()
wasRedirected = self.resolveRedirect(useHEAD = useHEAD)
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false """ try: wasRedirected = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg:...
return False, u'HTTP Redirect Loop: %s' % ' -> '.join(self.redirectChain + [self.url])
if useHEAD: redirChecker = LinkChecker(self.redirectChain[0]) return redirChecker.check(useHEAD = False) else: return False, u'HTTP Redirect Loop: %s' % ' -> '.join(self.redirectChain + [self.url])
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false """ try: wasRedirected = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg:...
return False, u'Long Chain of Redirects: %s' % ' -> '.join(self.redirectChain + [self.url])
if useHEAD: redirChecker = LinkChecker(self.redirectChain[0]) return redirChecker.check(useHEAD = False) else: return False, u'Long Chain of Redirects: %s' % ' -> '.join(self.redirectChain + [self.url])
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false """ try: wasRedirected = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg:...
return redirChecker.check()
return redirChecker.check(useHEAD = useHEAD)
def check(self): """ Returns True and the server status message if the page is alive. Otherwise returns false """ try: wasRedirected = self.resolveRedirect() except httplib.error, arg: return False, u'HTTP Error: %s' % arg except socket.error, arg: return False, u'Socket Error: %s' % arg except UnicodeEncodeError, arg:...
cat_namespace = wikipedia.getSite().category_namespace()
cat_namespace = wikipedia.getSite().category_namespaces()[0]
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...
wikipedia.output(u"Current categories: %s" % cats)
wikipedia.output(u"Current categories:") for curpl in cats: wikipedia.output(u"* %s" % cat.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...
nn=wikipedia.url2link(wikipedia.link2url(old[code]))
nn=wikipedia.url2link(wikipedia.link2url(new[code]))
def compareLanguages(old,new): removing=[] adding=[] modifying=[] for code,name in old.iteritems(): if not new.has_key(code): removing.append(code) elif old[code]!=new[code]: oo=wikipedia.url2link(wikipedia.link2url(old[code])) nn=wikipedia.url2link(wikipedia.link2url(old[code])) if oo!=nn: modifying.append(code) for c...
s=compareLanguages(old,new) if not s and only_if_status:
mods=compareLanguages(old,new) if not mods and only_if_status:
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
print s
print mods
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
status,reason,data=wikipedia.putPage(mylang,inname,newtext)
status,reason,data=wikipedia.putPage(mylang,inname,newtext,comment='Rob Hooft: robot '+mods)
def treesearch(code,name): arr={(code,name):None} # First make one step based on the language itself try: n=treestep(arr,code,name,abort_on_redirect=1) except wikipedia.IsRedirectPage: print "Is redirect page" return if n==0 and not arr[code,name]: print "Mother doesn't exist" return # Then add translations if we survi...
Page(self, "Non-existing page").get(force = True, sysop = sysop)
Page(self, "Wikipedia:Sandbox").get(force = True, sysop = sysop)
def getToken(self, getalways = True, getagain = False, sysop = False): if getagain or (getalways and ((sysop and not self._sysoptoken) or (not sysop and not self._token))): output(u"Getting page to get a token.") try: Page(self, "Non-existing page").get(force = True, sysop = sysop) except Error: pass if sysop: if not s...
sysop = (self.editRestriction is not None)
sysop = (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
catlib.change_category(article, original_cat, current_cat.titleWithoutNamespace())
catlib.change_category(article, original_cat, current_cat)
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...
catlink = catlib.Category(wikipedia.getSite(), 'Category:' + self.catTitle)
cat = catlib.Category(wikipedia.getSite(), 'Category:' + self.catTitle)
def run(self): catlink = catlib.Category(wikipedia.getSite(), 'Category:' + self.catTitle) # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_change) % self.catTitle) articles = catlink.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in ca...
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_change) % self.catTitle) articles = catlink.articles(recurse = 0)
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_change) % cat.title()) articles = cat.articles(recurse = 0)
def run(self): catlink = catlib.Category(wikipedia.getSite(), 'Category:' + self.catTitle) # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_change) % self.catTitle) articles = catlink.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in ca...
self.move_to_category(article, catlink, catlink)
self.move_to_category(article, cat, cat)
def run(self): catlink = catlib.Category(wikipedia.getSite(), 'Category:' + self.catTitle) # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg_change) % self.catTitle) articles = catlink.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in ca...
},
}
def __init__(self): family.Family.__init__(self) self.name = 'wikiquote' self.langs = { 'minnan':'zh-min-nan.wikiquote.org', 'nb':'no.wikiquote.org', 'zh-cn':'zh.wikiquote.org', 'zh-tw':'zh.wikiquote.org' } for lang in self.knownlanguages: self.langs[lang] = lang+'.wikiquote.org'
data = response.read() print response.status, response.reason
returned_html = response.read()
def post_multipart(host, selector, fields, files, cookies): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page...
return data
return response, returned_html
def post_multipart(host, selector, fields, files, cookies): """ Post fields and files to an http host as multipart/form-data. fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return the server's response page...
if not self.urlEncoding: self.url = self.url.encode('utf-8') self.url = urllib.quote(self.url) self.urlEncoding = 'utf-8'
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ if not self.urlEncoding: # URL is a ...
uo = wikipedia.MyURLopener() file = uo.open(self.url)
if '://' in self.url: uo = wikipedia.MyURLopener() file = uo.open(self.url) else: file = open(self.url) wikipedia.output('Reading file %s' % self.url)
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ if not self.urlEncoding: # URL is a ...
filename = filename.encode(self.targetSite.encoding())
encodedFilename = filename.encode(self.targetSite.encoding())
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ if not self.urlEncoding: # URL is a ...
returned_html = post_multipart(self.targetSite.hostname(),
response, returned_html = post_multipart(self.targetSite.hostname(),
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ if not self.urlEncoding: # URL is a ...
(('wpUploadFile', filename, contents),),
(('wpUploadFile', encodedFilename, contents),),
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ if not self.urlEncoding: # URL is a ...
success_msg = mediawiki_messages.get('successfulupload', site = self.targetSite) success_msgR = re.compile(re.escape(success_msg)) if success_msgR.search(returned_html):
if response.status == 302:
def upload_image(self, debug=False): """Gets the image at URL self.url, and uploads it to the target wiki. Returns the filename which was used to upload the image. If the upload fails, the user is asked whether to try again or not. If the user chooses not to retry, returns null. """ if not self.urlEncoding: # URL is a ...
if not (trailingChars or label):
if not trailingChars:
def cleanUpLinks(self, text): trailR = re.compile(self.site.linktrail()) # The regular expression which finds links. Results consist of four groups: # group title is the target page title, that is, everything before | or ]. # group section is the page section. It'll include the # to make life easier for us. # group lab...
else: output( u"DBG>>> Strange title: %s:%s" % (site.lang, title) )
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
Rcomment = re.compile("<!--.*?-->", re.M) while True: comment = Rcomment.search(thistxt) if not comment: break thistxt = thistxt[:comment.start()] + thistxt[comment.end():]
thistxt = re.sub("(?ms)<!--.*?-->", "", thistxt)
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())
Rnowiki = re.compile("<nowiki>.*?</nowiki>", re.M) while True: nowiki = Rnowiki.search(thistxt) if not nowiki: break thistxt = thistxt[:nowiki.start()] + thistxt[nowiki.end():]
thistxt = re.sub("(?ms)<nowiki>.*?</nowiki>", "", thistxt)
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())
result.append(page)
if page.sectionFreeTitle(): 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())
for i in range(len(title)): title[i] = title[i].strip() self._title = ':'.join(title)
self._title = ':'.join(title).strip()
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...
iend = txt.index('<div id="catlinks">')
iend = txt.index('<div class="printfooter">')
def _make_catlist(self, recurse = False, purge = False, site = None): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and subcategories of any subcategories are also retrieved.
except ValueError: iend = txt.index('<div class="printfooter">')
def _make_catlist(self, recurse = False, purge = False, site = None): """Make a list of all articles and categories that are in this category. If recurse is set to True, articles and subcategories of any subcategories are also retrieved.
'af' : lambda v: slh( v, [u'Januarie', u'Februarie', u'Maart', u'April', u'Mei', u'Junie', u'Julie', u'Augustus', u'September', u'Oktober', u'November', u'Desember'] ), 'als': lambda v: slh( v, [u'Januar', u'Februar', u'März', u'April', u'Mai', u'Juni', u'Juli', u'August', u'September', u'Oktober', u'November...
'af' : lambda v: slh( v, [u"Januarie", u"Februarie", u"Maart", u"April", u"Mei", u"Junie", u"Julie", u"Augustus", u"September", u"Oktober", u"November", u"Desember"] ), 'als': lambda v: slh( v, [u"Januar", u"Februar", u"März", u"April", u"Mai", u"Juni", u"Juli", u"August", u"September", u"Oktober", u"November...
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo...
'eo' : lambda v: slh( v, [u'Januaro', u'Februaro', u'Marto', u'Aprilo', u'Majo', u'Junio', u'Julio', u'Aŭgusto', u'Septembro', u'Oktobro', u'Novembro', u'Decembro'] ), 'es' : lambda v: slh( v, [u'Enero', u'Febrero', u'Marzo', u'Abril', u'Mayo', u'Junio', u'Julio', u'Agosto', u'Septiembre', u'Octubre', u'Novie...
'eo' : lambda v: slh( v, [u"Januaro", u"Februaro", u"Marto", u"Aprilo", u"Majo", u"Junio", u"Julio", u"Aŭgusto", u"Septembro", u"Oktobro", u"Novembro", u"Decembro"] ), 'es' : lambda v: slh( v, [u"enero", u"febrero", u"marzo", u"abril", u"mayo", u"junio", u"julio", u"agosto", u"septiembre", u"octubre", u"novie...
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo...
'simple' : lambda v: dh_noConv( v, u'%dth century' ),
'simple' : lambda v: multi( v, [ (lambda x: dh_noConv( x, u'%dst century' ), lambda x: x == 1 or (x > 20 and x%10 == 1)), (lambda x: dh_noConv( x, u'%dnd century' ), lambda x: x == 2 or (x > 20 and x%10 == 2)), (lambda x: dh_noConv( x, u'%drd century' ), lambda x: x == 3 or (x > 20 and x%10 == 3)), (lambda x: dh_noCon...
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo...
addFmt( yrMnthFmts, 'af', True, makeMonthNamedList( 'af', u"%s %%d", True )) addFmt( yrMnthFmts, 'ang',True, [ None, None, None, None, None, None, None, None, None, None, None, u"Gēolmōnaþ %d" ]) addFmt( yrMnthFmts, 'de', True, makeMonthNamedList( 'de', u"%s %%d", True )) addFmt( yrMnthFmts, 'el', True, makeMonthNa...
addFmt( yrMnthFmts, 'af', True, makeMonthNamedList( 'af', u"%s %%d", True )) addFmt( yrMnthFmts, 'ang',True, [ None, None, None, None, None, None, None, None, None, None, None, u"Gēolmōnaþ %d" ]) addFmt( yrMnthFmts, 'de', True, makeMonthNamedList( 'de', u"%s %%d", True )) addFmt( yrMnthFmts, 'el', True, ...
def makeMonthNamedList( lang, pattern, makeUpperCase = None ): """Creates a list of 12 elements based on the name of the month. The language-dependent month name is used as a formating argument to the pattern. The pattern must be have one %s that will be replaced by the localized month name. Use %%d for any other param...
import wikipedia
def printMonthArray( lang, pattern, capitalize ): """ """ import wikipedia for s in makeMonthNamedList( lang, pattern, capitalize ): wikipedia.output( s )
import wikipedia
start,end,step = formatLimits[m] if showAll: wikipedia.output(u"Limits: from %d to %d, with step %d" % (start,stop,step))
def testMapEntry( showAll, m, year, testYear ): """This is a test function, to be used interactivelly to test the validity of the above maps. To test, run this function with the map name, year to be tested, and the final year expected. Usage example: run python interpreter >>> import date >>> date.testMapEntry( 'Decade...
+ "<a href=.+? class=\"new\" title=.+?>.+?<\/a><\/p>\n"
+ "<a href=.+? title=.+?>.+?<\/a><\/p>\n"
def refresh_messages(): host = wikipedia.family.hostname(wikipedia.mylang) # broken redirect maintenance page's URL url = wikipedia.family.allmessages_address(wikipedia.mylang) print 'Retrieving MediaWiki messages...' allmessages, charset = wikipedia.getUrl(host,url) #f=open('/home/daniel/allmessages.html', 'r') #allm...
x = x.encode(encoding) return x
return x.decode(encoding)
def url2unicode(percentname, site): # Does the input string contain non-ascii characters? In that case, # it is not really an url, and we do not have to unquote it.... for c in percentname: if ord(c)>128: x=percentname break else: # Before removing the % encoding, make sure it is an ASCII string. # unquote doesn't work...
entryR = re.compile('<li>(?P<date>.+?) <a href=".+?" title="(?P<title>.+?)">.+?</a> \((?P<length>\d+)(.+?)\) \. \. (?P<loggedin><a href=".+?" title=".+?">)?(?P<username>.+?)(</a>)?( <em>\((?P<comment>.+?)\)</em>)?</li>')
entryR = re.compile('<li[^>]*>(?P<date>.+?) \S*?<a href=".+?" title="(?P<title>.+?)">.+?</a>.+?\((?P<length>\d+)(.+?)\) \. \. (.*?)(?P<loggedin><a href=".+?" title="(?P<username>.+?)">)')
def newpages(self, number = 10, repeat = False): """Generator which yields new articles subsequently. It starts with the article created 'number' articles ago (first argument). When these are all yielded it fetches NewPages again. If there is no new page, it blocks until there is one, sleeping between subsequent fetche...
comment = m.group('comment')
def newpages(self, number = 10, repeat = False): """Generator which yields new articles subsequently. It starts with the article created 'number' articles ago (first argument). When these are all yielded it fetches NewPages again. If there is no new page, it blocks until there is one, sleeping between subsequent fetche...
yield page, date, length, loggedIn, username, comment
yield page, date, length, loggedIn, username, None
def newpages(self, number = 10, repeat = False): """Generator which yields new articles subsequently. It starts with the article created 'number' articles ago (first argument). When these are all yielded it fetches NewPages again. If there is no new page, it blocks until there is one, sleeping between subsequent fetche...
defdis = self.site().family.disambig( "_default" )
def isDisambig(self): if not hasattr(self, '_isDisambig'): defdis = self.site().family.disambig( "_default" ) locdis = self.site().family.disambig( self._site.lang )
if tn in defdis or tn in locdis:
if tn in locdis:
def isDisambig(self): if not hasattr(self, '_isDisambig'): defdis = self.site().family.disambig( "_default" ) locdis = self.site().family.disambig( self._site.lang )
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(),msg_change) % oldCat.title())
wikipedia.setAction(wikipedia.translate(wikipedia.getSite(),msg_change) % self.oldCat.title())
def __init__(self, oldCatTitle, newCatTitle): self.oldCat = catlib.Category(wikipedia.getSite(), 'Category:' + oldCatTitle) self.newCatTitle = newCatTitle # get edit summary message wikipedia.setAction(wikipedia.translate(wikipedia.getSite(),msg_change) % oldCat.title())
'nds': [u'Begreepkloren'],
'nds': [u'Mehrdüdig Begreep'],
def __init__(self): family.Family.__init__(self) self.name = 'wikipedia'
output(u"ERROR> link from %s to %s:%s has leading colon?!" % (self, newsite, newname))
output(u"ERROR> link from %s to %s:%s has leading colon?!" % (self.linkname(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s has leading space?!" % (self, newsite, newname))
output(u"ERROR> link from %s to %s:%s has leading space?!" % (self.linkname(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s is invalid encoding?!" % (self, newsite, newname))
output(u"ERROR> link from %s to %s:%s is invalid encoding?!" % (self.linkname(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s contains invalid character?!" % (self, newsite, newname))
output(u"ERROR> link from %s to %s:%s contains invalid character?!" % (self.linkname(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
output(u"ERROR> link from %s to %s:%s contains invalid unicode reference?!" % (self, newsite, newname))
output(u"ERROR> link from %s to %s:%s contains invalid unicode reference?!" % (self.linkname(), newsite, newname))
def interwiki(self): """A list of interwiki links in the page. This will retrieve the page text to do its work, so it can raise the same exceptions that are raised by the get() method.
templateR=re.compile(r'\{\{([mM][sS][gG]:)?[' + self.old[0].upper() + self.old[0].lower() + ']' + self.old[1:] + '(?P<sortkey>\|[^}]+)?}}')
templateR=re.compile(r'\{\{([mM][sS][gG]:)?[' + self.old[0].upper() + self.old[0].lower() + ']' + self.old[1:] + '(?P<sortkey>\|[^}]+|)}}')
def run(self): # regular expression to find the original template. # {{msg:vfd}} does the same thing as {{msg:Vfd}}, so both will be found. # The new syntax, {{vfd}}, will also be found. templateR=re.compile(r'\{\{([mM][sS][gG]:)?[' + self.old[0].upper() + self.old[0].lower() + ']' + self.old[1:] + '(?P<sortkey>\|[^}]+...
print "DBG> addEntity:", repr(name), repr(result)
def addEntity(name): """Convert a unicode name into ascii name with entities""" import htmlentitydefs result = '' for c in name: if ord(c) < 128: result += str(c) else: for k, v in htmlentitydefs.entitydefs.iteritems(): if (len(v) == 1 and ord(c) == ord(v)) or v == '&#%d;'%ord(c): result += '&%s;' % k break else: raise...
wikipedia.action += wrd
wikipedia.setAction('Robot-assisted disambiguation '+wrd)
def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt)
print "== %s =="%(refpl),m.start(),m.end()
print "== %s =="%(refpl)
def getreferences(pl): host = wikipedia.langs[pl.code()] url="/w/wiki.phtml?title=Speciaal:Whatlinkshere&target=%s"%(pl.urlname()) txt,charset=wikipedia.getUrl(host,url) Rref=re.compile('<li><a href.* title="([^"]*)"') return Rref.findall(txt)
'ia' : lambda v: dh_dayOfMnth( v, u'%d de decembre' ),
'ia' : lambda v: dh_dayOfMnth( v, u'%d de Decembre' ),
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalTo...
self.loggedin = 'Userlogin' not in txt
self._loggedin = 'Userlogin' not in txt
def loggedin(self, check = False): if not hasattr(self,'_loggedin'): self._fill() if check: txt = getPage(self, 'Non-existing page', get_edit_page = False) self.loggedin = 'Userlogin' not in txt return self._loggedin
if not globalvar.autonomous:
if globalvar.autonomous: if self.inpl.isDisambig() and not pl.isDisambig(): wikipedia.output(u"NOTE: Ignoring link from disambiguation page %s to non-disambiguation %s" % (self.inpl.aslink(forceInterwiki = True), pl.aslink(forceInterwiki = True))) del self.done[pl] elif not self.inpl.isDisambig() and pl.isDisambig(): w...
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 ...
firstLabel = '"%s:%s"' % (inpl.site().language(), wikipedia.unicode2html(inpl.title(), 'ascii'))
firstLabel = '"%s:%s"' % (self.inpl.site().language(), wikipedia.unicode2html(inpl.title(), 'ascii'))
def createGraph(self): import pydot # create empty graph graph = pydot.Dot() graph.add_node(pydot.Node('start', shape = 'point')) for page in self.foundin.iterkeys(): # a node for each found page node = pydot.Node('"%s:%s"' % (page.site().language(), wikipedia.unicode2html(page.title(), 'ascii')), shape = 'rectangle') ...
result[k] = v[answer-1] break
try: result[k] = v[answer-1] except IndexError: pass else: break
def assemble(self): # No errors have been seen so far nerr = 0 # Build up a dictionary of all links found, with the code as key. # Each value will be a list. 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....
pl = wikipedia.PageLink(wikipedia.getSit(), refpage)
pl = wikipedia.PageLink(wikipedia.getSite(), refpage)
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...
s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[0]) + ",".join([x.lang for x in adding])
s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[0]) + " " + ", ".join([x.lang for x in adding])
def compareLanguages(old, new): removing = [] adding = [] modifying = [] mysite = wikipedia.getSite() for site in old.keys(): if site not in new: removing.append(site) elif 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:"...
s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[1]) + ",".join([x.lang for x in removing])
s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[1]) + " " + ", ".join([x.lang for x in removing])
def compareLanguages(old, new): removing = [] adding = [] modifying = [] mysite = wikipedia.getSite() for site in old.keys(): if site not in new: removing.append(site) elif 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:"...
s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[2]) + ",".join([x.lang for x in modifying])
s = s + " %s:" % (wikipedia.translate(mysite.lang, msg)[2]) + " " + ", ".join([x.lang for x in modifying])
def compareLanguages(old, new): removing = [] adding = [] modifying = [] mysite = wikipedia.getSite() for site in old.keys(): if site not in new: removing.append(site) elif 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:"...
i = 0 for page in self.pageGenerator: if page not in globalvar.skip: i += 1
for i in range(number): try: page = self.pageGenerator.next() while page in globalvar.skip: page = self.pageGenerator.next()
def generateMore(self, number): """Generate more subjects. This is called internally when the list of subjects becomes to small, but only if there is a PageGenerator""" fs = self.firstSubject() if fs: wikipedia.output(u"NOTE: The first unfinished subject is " + fs.pl().aslink()) print "NOTE: Number of pages queued is %...
if i >= number: return self.pageGenerator = None
except StopIteration: self.pageGenerator = None break
def generateMore(self, number): """Generate more subjects. This is called internally when the list of subjects becomes to small, but only if there is a PageGenerator""" fs = self.firstSubject() if fs: wikipedia.output(u"NOTE: The first unfinished subject is " + fs.pl().aslink()) print "NOTE: Number of pages queued is %...
bot.setPageGenerator(hintlessPageGen)
bot.setPageGenerator(iter(hintlessPageGen))
def readWarnfile(filename, sa): import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints (hints, removeHints) = reader.getHints() pages = hints.keys() for page in pages: # The WarnfileReader gives us a list of pagelinks, but titletranslate.py expects a list of strings, so we convert it back...
ns = []
namespaces = []
def category_namespaces(code): ns = [] if not category.has_key(code): #print "DBG> No category namespace known for %s" % code import mediawiki_messages ns.append(mediawiki_messages.get('nstab-category', lang = code)) else: ns.append(category[code]) ns.append(category[code].lower()) if category[code] != category['en']: ...
ns.append(mediawiki_messages.get('nstab-category', lang = code))
namespace_title = mediawiki_messages.get('nstab-category', lang = code)
def category_namespaces(code): ns = [] if not category.has_key(code): #print "DBG> No category namespace known for %s" % code import mediawiki_messages ns.append(mediawiki_messages.get('nstab-category', lang = code)) else: ns.append(category[code]) ns.append(category[code].lower()) if category[code] != category['en']: ...
ns.append(category[code]) ns.append(category[code].lower()) if category[code] != category['en']: ns.append(category['en']) ns.append(category['en'].lower()) return ns
namespace_title = category[code] namespaces.append(namespace_title) namespaces.append(namespace_title.lower()) if namespace_title != category['en']: namespaces.append(category['en']) namespaces.append(category['en'].lower()) return namespaces
def category_namespaces(code): ns = [] if not category.has_key(code): #print "DBG> No category namespace known for %s" % code import mediawiki_messages ns.append(mediawiki_messages.get('nstab-category', lang = code)) else: ns.append(category[code]) ns.append(category[code].lower()) if category[code] != category['en']: ...
ns = wikipedia.family.category_namespaces(wikipedia.mylang) cat_namespace = ns[0].encode(wikipedia.myencoding())
cat_namespace = wikipedia.family.category_namespace(wikipedia.mylang)
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...