rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
answer=raw_input('submit y/n ?')
if ask: answer=raw_input('submit y/n ?') else: answer='y'
def do(year): page=str(year) if debug: page='Robottest' text=wikipedia.getPage(mylang,page) orgtext=text # Replace all of these by the standardized formulae text=R4.sub("\r\n",text) text=R5.sub("\r\n\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R10.sub("\r\n",text) text=R11.sub("\r\n",text) te...
self.site._fill()
self.site._loadCookies()
def login(self):#, anonymous): """Initialises site and username data"""#, or anonymous""" if False:#anonymous: self.site = wikipedia.getSite(user=None) else: self.username = self.options.username or wikipedia.input(u"Username:") self.site = wikipedia.getSite(user=self.username) self.site._fill() # load cookies if not s...
cookie = login.login(self.site, self.username, password)
cookie = login.LoginManager(self.username, password, self.site)
def login(self):#, anonymous): """Initialises site and username data"""#, or anonymous""" if False:#anonymous: self.site = wikipedia.getSite(user=None) else: self.username = self.options.username or wikipedia.input(u"Username:") self.site = wikipedia.getSite(user=self.username) self.site._fill() # load cookies if not s...
login.storecookiedata(cookie, self.site, self.username)
def login(self):#, anonymous): """Initialises site and username data"""#, or anonymous""" if False:#anonymous: self.site = wikipedia.getSite(user=None) else: self.username = self.options.username or wikipedia.input(u"Username:") self.site = wikipedia.getSite(user=self.username) self.site._fill() # load cookies if not s...
('pages', pagenames),
('pages', UnicodeToAsciiHtml(pagenames)),
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]) data = urlencode(( ('action', 'submit'), ('pages', pagenames), ('curonly', 'True'), )) heade...
ccToolkit = CosmeticChangesToolkit(page.site(), debug = True) changedText = ccToolkit.change(page.get()) if changedText != page.get(): if not self.acceptall: choice = wikipedia.inputChoice(u'Do you want to accept these changes?', ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N') if choice in ['a', 'A']: self.acceptall = Tru...
try: ccToolkit = CosmeticChangesToolkit(page.site(), debug = True) changedText = ccToolkit.change(page.get()) if changedText != page.get(): if not self.acceptall: choice = wikipedia.inputChoice(u'Do you want to accept these changes?', ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N') if choice in ['a', 'A']: self.acceptall ...
def run(self): for page in self.generator: ccToolkit = CosmeticChangesToolkit(page.site(), debug = True) changedText = ccToolkit.change(page.get()) if changedText != page.get(): if not self.acceptall: choice = wikipedia.inputChoice(u'Do you want to accept these changes?', ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N') if...
for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'cosmetic_changes') if arg: if arg.startswith('-start:'): gen = pagegenerators.AllpagesPageGenerator(arg[7:]) elif arg.startswith('-ref:'): referredPage = wikipedia.Page(wikipedia.getSite(), arg[5:]) gen = pagegenerators.ReferringPageGenerator(referredPage) elif ...
for arg in wikipedia.handleArgs(): if arg.startswith('-start:'): gen = pagegenerators.AllpagesPageGenerator(arg[7:]) elif arg.startswith('-ref:'): referredPage = wikipedia.Page(wikipedia.getSite(), arg[5:]) gen = pagegenerators.ReferringPageGenerator(referredPage) elif arg.startswith('-links:'): linkingPage = wikipedia...
def main(): #page generator gen = None pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'cosmetic_changes') if arg: if arg.startswith('-start:'): gen = pagegenerators.AllpagesPageGenerator(arg[7:]) elif arg.startswith('-ref:'): referredPage = wikipedia.Page(wikipedia.getSite(), arg[5:]) gen = pag...
wikipedia.showHelp('cosmetic_changes')
wikipedia.showHelp()
def main(): #page generator gen = None pageTitle = [] for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'cosmetic_changes') if arg: if arg.startswith('-start:'): gen = pagegenerators.AllpagesPageGenerator(arg[7:]) elif arg.startswith('-ref:'): referredPage = wikipedia.Page(wikipedia.getSite(), arg[5:]) gen = pag...
wikipedia.output(u'ERROR: Username for %s:%s is undefined.\nIf you have an account for that site, please add such a line to user-config.py:\n\nusernames[\'%s\'][\'%s\'] = \'myUsername\'')
wikipedia.output(u'ERROR: Username for %s:%s is undefined.\nIf you have an account for that site, please add such a line to user-config.py:\n\nusernames[\'%s\'][\'%s\'] = \'myUsername\'' % (self.site.family.name, self.site.lang, self.site.family.name, self.site.lang))
def __init__(self, username = None, password = None, site = None): self.site = site or wikipedia.getSite() try: self.username = username or config.usernames[self.site.family.name][self.site.lang] except: wikipedia.output(u'ERROR: Username for %s:%s is undefined.\nIf you have an account for that site, please add such a ...
print 'testing'
def wikiwrap(self): print 'testing' for subentry in self.subentries: print 'testing' entry='test'
print 'testing' entry='test'
entry=subentry.wikiwrap(self.wikilang) + '\n\n'
def wikiwrap(self): print 'testing' for subentry in self.subentries: print 'testing' entry='test'
subentry=langheader(wikilang) + '\n'
subentry=langheader[wikilang] + '\n'
def wikiwrap(self,wikilang): for meaning in self.meanings: subentry=langheader(wikilang) + '\n' # langheader is a dictionary that has the proper way to create a header indicating the language of a subentry for this Wiktionary term=meaning.term subentry+=posheader(wikilang,term.pos) # posheader is a dictionary that has ...
subentry+=posheader(wikilang,term.pos)
subentry+=posheader[wikilang]
def wikiwrap(self,wikilang): for meaning in self.meanings: subentry=langheader(wikilang) + '\n' # langheader is a dictionary that has the proper way to create a header indicating the language of a subentry for this Wiktionary term=meaning.term subentry+=posheader(wikilang,term.pos) # posheader is a dictionary that has ...
subentry+=term.getTerm + ' ' + term.getGender + ' ' + meaning.definition
subentry= subentry + term.getTerm() + ' ' + term.getGender() + ' ' + meaning.definition()
def wikiwrap(self,wikilang): for meaning in self.meanings: subentry=langheader(wikilang) + '\n' # langheader is a dictionary that has the proper way to create a header indicating the language of a subentry for this Wiktionary term=meaning.term subentry+=posheader(wikilang,term.pos) # posheader is a dictionary that has ...
return(gender)
return(self.gender)
def getGender(self): return(gender)
apage = WiktionaryEntry('nl',u'iets')
apage = WiktionaryEntry('nl',u'iemand')
def wikiwrap(self,wikilang): return()
frtrans = Noun('fr',u"quelque'chose")
frtrans = Noun('fr',u"quelqu'un")
def wikiwrap(self,wikilang): return()
entrans = Noun('en',u'something')
entrans = Noun('en',u'somebody')
def wikiwrap(self,wikilang): return()
ameaning = Meaning(u'een ding',aword)
ameaning = Meaning(u'een persoon',aword)
def wikiwrap(self,wikilang): return()
t= apage.wikiwrap
t=apage.wikiwrap()
def wikiwrap(self,wikilang): return()
if choice2 == 'y': redir_text = '
if choice == 'y': redir_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 code in ['meta','bs','ru','eo','ja','zh','hi','he','hu','pl','ko','cs','el','sl','ro']:
if code in ['meta','bs','ru','eo','ja','zh','hi','he','hu','pl','ko','cs','el','sl','ro','hr','tr']:
def code2encoding(code): if code in ['meta','bs','ru','eo','ja','zh','hi','he','hu','pl','ko','cs','el','sl','ro']: return 'utf-8' return 'iso-8859-1'
('wpOldTitle', self.title()), ('wpNewTitle', newtitle),
('wpOldTitle', self.title().encode(self.site().encoding())), ('wpNewTitle', newtitle.encode(self.site().encoding())),
def move(self, newtitle, reason = None, movetalkpage = True, sysop = False): if reason == None: reason = "Pagemove by bot" if self.namespace() // 2 == 1: movetalkpage = False host = self.site().hostname() address = self.site().move_address() self.site().forceLogin(sysop = sysop) token = self.site().getToken(self, sysop...
v = urllib.quote(v.encode('utf8'))
v = urllib.quote(v)
def urlencode(query): """This can encode a query so that it can be sent as a query using a http POST request""" l=[] for k, v in query: k = urllib.quote(k) v = urllib.quote(v.encode('utf8')) l.append(k + '=' + v) return '&'.join(l)
Returns cookie data if succesful, False otherwise."""
Returns cookie data if succesful, None otherwise."""
def getCookie(self, remember=True): """Login to wikipedia. remember Remember login (default: True) Returns cookie data if succesful, False otherwise.""" data = {"wpName": self.username, "wpPassword": self.password, "wpLoginattempt": "Aanmelden & Inschrijven", # dutch button label seems to work for all wikis "wpRe...
return False
return None
def getCookie(self, remember=True): """Login to wikipedia. remember Remember login (default: True) Returns cookie data if succesful, False otherwise.""" data = {"wpName": self.username, "wpPassword": self.password, "wpLoginattempt": "Aanmelden & Inschrijven", # dutch button label seems to work for all wikis "wpRe...
filename = 'login-data/%s-%s-%slogin.data' % (self.site.family.name, self.site.lang, self.username)
filename = 'login-data/%s-%s-login.data' % (self.site.family.name, self.site.lang)
def storecookiedata(self, data): """ Stores cookie data.
break
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.
loc = len(page)
loc = len(text)
def spellcheck(page): text = page if correct_html_codes: text = removeHTML(text) loc = 0 while True: wordsearch = re.compile(r'([\s\=\<\>\_]*)([^\s\=\<\>\_]+)') match = wordsearch.search(text,loc) if not match: # No more words on this page break loc += len(match.group(1)) bigword = Word(match.group(2)) smallword = bigw...
yield PageLink(mylang, url2link(hit, code = mylang, incode = mylang))
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...
def autonomous_problem(pl):
def autonomous_problem(pl,reason=''):
def autonomous_problem(pl): if autonomous: f=open('autonomous_problem.dat','a') f.write("%s\n"%pl) f.close() sys.exit(1)
f.write("%s\n"%pl)
f.write("%s {%s}\n"%(pl,reason))
def autonomous_problem(pl): if autonomous: f=open('autonomous_problem.dat','a') f.write("%s\n"%pl) f.close() sys.exit(1)
newcode,newname=h.split(':') x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None
codes,newname=h.split(':') if codes=='all': codes=wikipedia.biglangs else: codes=codes.split(',') for newcode in codes: x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None
def autotranslate(pl,arr,same=0): if same: return sametranslate(pl,arr) if hints: for h in hints: newcode,newname=h.split(':') x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None # Autotranslate dates into some other languages, the rest will come from # existing interwiki links. Rdate=re.compile('(\d+)_(...
Rdate=re.compile('(\d+)_(%s)'%('|'.join(datetable.keys()))) m=Rdate.match(pl.linkname()) if m: for newcode,fmt in datetable[m.group(2)].items(): newname=fmt%int(m.group(1)) x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None return
if mylang==datetablelang: Rdate=re.compile('(\d+)_(%s)'%('|'.join(datetable.keys()))) m=Rdate.match(pl.linkname()) if m: for newcode,fmt in datetable[m.group(2)].items(): newname=fmt%int(m.group(1)) x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None return
def autotranslate(pl,arr,same=0): if same: return sametranslate(pl,arr) if hints: for h in hints: newcode,newname=h.split(':') x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None # Autotranslate dates into some other languages, the rest will come from # existing interwiki links. Rdate=re.compile('(\d+)_(...
Ryear=re.compile('^(\d+)_v._Chr.') m=Ryear.match(pl.linkname()) if m: for newcode in wikipedia.langs: fmt = yearBCfmt.get(newcode) if fmt: newname = fmt%int(m.group(1)) x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None return
if mylang=='nl': Ryear=re.compile('^(\d+)_v._Chr.') m=Ryear.match(pl.linkname()) if m: for newcode in wikipedia.langs: fmt = yearBCfmt.get(newcode) if fmt: newname = fmt%int(m.group(1)) x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None return
def autotranslate(pl,arr,same=0): if same: return sametranslate(pl,arr) if hints: for h in hints: newcode,newname=h.split(':') x=wikipedia.PageLink(newcode,newname) if x not in arr: arr[x]=None # Autotranslate dates into some other languages, the rest will come from # existing interwiki links. Rdate=re.compile('(\d+)_(...
for newpl in pl.interwiki(): if newpl not in arr: print "NOTE: from %s we got the new %s"%(pl,newpl) arr[newpl]=None n+=1
if bigger(pl): print "NOTE: %s is bigger than %s, not following references"%(pl,inpl) else: for newpl in pl.interwiki(): if newpl not in arr: print "NOTE: from %s we got the new %s"%(pl,newpl) arr[newpl]=None n+=1
def treestep(arr,pl,abort_on_redirect=0): assert arr[pl] is None print "Getting %s"%pl n=0 try: text=pl.get() except wikipedia.NoPage: print "---> Does not actually exist" arr[pl]='' return 0 except wikipedia.LockedPage: print "---> Locked" arr[pl]=1 return 0 except wikipedia.IsRedirectPage,arg: if abort_on_redirect an...
if pl.code()==mylang:
if pl.code()==mylang and m[pl]:
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 translations" ...
autonomous_problem(inpl)
autonomous_problem(inpl,'Someone refers to another page with us')
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 translations" ...
autonomous_problem(inpl)
autonomous_problem(inpl,'There are alternatives in %s'%pl.code())
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 translations" ...
autonomous_problem(inname)
autonomous_problem(inpl,'removing a language')
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 translations" ...
supercats = get_supercats(cat)
supercats = get_supercats(cat)[:]
def treeview(cat, max_depth, current_depth = 0, supercat = None): ''' Returns a multi-line string which contains a tree view of all subcategories of cat, up to level max_depth. Parameters: * cat - a CatLink which will be the tree's root * current_depth - the current level in the tree (for recursion) * supercat - the C...
print 'bla2'
def __init__(self, parent = None): print 'bla2' if parent == None: # create a new window parent = Tk() self.myParent = parent
def getVersionHistory(self, force = False):
def getVersionHistory(self, forceReload = False):
def getVersionHistory(self, force = 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() host = site.hostname() url = site.family.version_history_address(site, self.urlname())
if not hasattr(self, '_versionhistory') or force = True:
if not hasattr(self, '_versionhistory') or forceReload:
def getVersionHistory(self, force = 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() host = site.hostname() url = site.family.version_history_address(site, self.urlname())
Page(self, "Wikipedia:Sandbox").get(force = True, sysop = sysop)
Page(self, "%s:Sandbox" % self.family.namespace(self.lang, 4)).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, "Wikipedia:Sandbox").get(force = True, sysop = sysop) except UserBlocked: raise except Erro...
codes, newname=h.split(':')
codes, newname = h.split(':', 1)
def autotranslate(pl, arr, same=0): if same: return sametranslate(pl, arr) if hints: for h in hints: codes, newname=h.split(':') if codes == 'all': codes = wikipedia.biglangs else: codes = codes.split(',') for newcode in codes: x = wikipedia.PageLink(newcode, newname) if x not in arr: arr[x] = None # Autotranslate date...
print data
output(data, decoder = code2encoding(mylang))
def putPage(code, name, text, comment = None, watchArticle = False, minorEdit = True, newPage = False): """Upload 'text' on page 'name' to the 'code' language wikipedia. Use of this routine can normally be avoided; use PageLink.put instead. """ import httplib put_throttle() host = family.hostname(code) address = family...
category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the category will be removed.
category newCat. Moves subcategories of oldCat as well. oldCat and newCat should be Category objects. If newCat is None, the category will be removed.
def change_category(article, oldCat, newCat, comment=None): """ Given an article which is in category oldCat, moves it to category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the...
for cat in cats[:]:
for i in range(len(cats)): cat = cats[i]
def change_category(article, oldCat, newCat, comment=None): """ Given an article which is in category oldCat, moves it to category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the...
sortKey = cat.sortKey cats.remove(cat) removed = True if not removed: wikipedia.output(u'ERROR: %s is not in category %s!' % (article.aslink(), oldCat.title())) return if newCat is not None: newCat = Category(site, newCat.title(), sortKey = sortKey) cats.append(newCat) text = article.get() text = wikipedia.replaceCateg...
sortKey = cat.sortKey if not newCat: cats = cats[:i] + cats[i+1:] else: newCat = Category(site, newCat.title(), sortKey = sortKey) cats = cats[:i] + [newCat] + cats[i+1:] text = article.get() text = wikipedia.replaceCategoryLinks(text, cats) article.put(text, comment) return wikipedia.output(u'ERROR: %s is not in categ...
def change_category(article, oldCat, newCat, comment=None): """ Given an article which is in category oldCat, moves it to category called newCatTitle. Moves subcategories of oldCat as well. oldCat should be a Category object, newCatTitle should be the new name as a string, without namespace. If newCatTitle is None, the...
else: newURL = '%s://%s/%s' % (self.protocol, self.host, redirTarget)
else: directory = self.path[:self.path.rindex('/') + 1] while redirTarget.startswith('../'): redirTarget = redirTarget[3:] directory = directory[:-1] directory = directory[:directory.rindex('/') + 1] newURL = '%s://%s%s%s' % (self.protocol, self.host, directory, redirTarget)
def resolveRedirect(self): ''' Requests the header from the server. If the page is an HTTP redirect, returns the redirect target URL as a string. Otherwise returns None. ''' conn = httplib.HTTPConnection(self.host) conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse() n...
print num,code
def _addlang(self, code, location, namespaces): """Add a new language to the langs and namespaces of the family. This is supposed to be called in the constructor of the family.""" self.langs[code] = location for num, val in namespaces.items(): print num,code self.namespaces[num][code]=val
if not config.categories_last:
if not code in config.categories_last:
def replaceCategoryLinks(oldtext, new, code = None): """Replace the category links given in the wikitext given in oldtext by the new links given in new. 'new' should be a list of category pagelink objects. """ if code is None: code = mylang # first remove interwiki links and add them later, so that # interwiki tags ap...
newcat = wikipedia.input('Category to add (do not give namespace) : ') newcat = unicode(newcat, config.console_encoding)
newcat = wikipedia.input('Category to add (do not give namespace) : ', encode = True) newcat = newcat
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...
conn = httplib.HTTPConnection(self.host)
if self.scheme == 'http': conn = httplib.HTTPConnection(self.host) elif self.scheme == 'https': conn = httplib.HTTPSConnection(self.host)
def resolveRedirect(self): ''' Requests the header from the server. If the page is an HTTP redirect, returns the redirect target URL as a string. Otherwise returns None. ''' conn = httplib.HTTPConnection(self.host) conn.request('HEAD', '%s%s' % (self.path, self.query), None, self.header) response = conn.getresponse() i...
conn = httplib.HTTPConnection(self.host)
if self.scheme == 'http': conn = httplib.HTTPConnection(self.host) elif self.scheme == 'https': conn = httplib.HTTPSConnection(self.host)
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:...
edittime[code, link2url(name, code)] = 0
edittime[code, link2url(name, code)] = "0"
def getPage(code, name, do_edit = 1, do_quote = 1): """Get the contents of page 'name' from the 'code' language wikipedia Do not use this directly; use the PageLink object instead.""" output(url2unicode("Getting page %s:%s"%(code,name), language = code)) host = family.hostname(code) name = re.sub(' ', '_', name) if not...
if edittime[code, name] == 0:
if edittime[code, name] == "0":
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.""" output(url2unicode("Getting page %s:%s"%(code,name), language = code)) host = family.hostname(code) name = re.sub(' ', '_', name) if not...
pass
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.""" output(url2unicode("Getting page %s:%s"%(code,name), language = code)) host = family.hostname(code) name = re.sub(' ', '_', name) if not...
title = url2unicode(title, site = site)
title = url2unicode(title, site = insite)
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...
result[insite.getSite(code = lang)] = Page(insite.getSite(code = lang), pagetitle)
result[insite.getSite(code = lang)] = Page(insite.getSite(code = lang), pagetitle, insite=insite)
def getLanguageLinks(text, insite = None, pageLink = "[[]]"): """ Returns a dictionary with language codes as keys and Page objects as values for each interwiki link found in the text. Do not call this routine directly, use Page objects instead""" if insite == None: insite = getSite() result = {} # Ignore interwiki lin...
self.preload(somePages) for refpl in somePages: yield refpl
if somePages != []: self.preload(somePages) for refpl in somePages: yield refpl
def generate(self): # this array will contain up to 20 pages and will be flushed # after these pages have been preloaded. somePages = [] i = 0 for pl in self.generator.generate(): i += 1 somePages.append(pl) # We don't want to load too many pages at once using XML export. # We only get 20 at a time. if i >= self.pageNu...
The URLs are dict's keys, and values are lists of tuples where each tuple
The URLs are dictionary keys, and values are lists of tuples where each tuple
def run(self): linkChecker = LinkChecker(self.url) try: ok, message = linkChecker.check() except: wikipedia.output('Exception while processing URL %s in page %s' % (self.url, self.page.title())) raise if ok: if self.history.setLinkAlive(self.url): wikipedia.output('*Link to %s in [[%s]] is back alive.' % (self.url, sel...
sure that two LinkCheckerThreads can't access the queue at the same time.
sure that two LinkCheckerThreads can not access the queue at the same time.
def save(self): """ Saves the .dat file to disk. """ datfile = open(self.datfilename, 'w') self.historyDict = pickle.dump(self.historyDict, datfile) datfile.close()
if config.report_dead_links_on_talk:
if globalvar.talk:
def __init__(self, generator, start ='!'): self.generator = generator self.start = start if config.report_dead_links_on_talk: reportThread = DeadLinkReportThread() # thread dies when program terminates # reportThread.setDaemon(True) reportThread.start() else: reportThread = None self.history = History(reportThread)
for arg in wikipedia.handleArgs():
args = wikipedia.handleArgs() args = globalvar.handleArgs(args) for arg in args:
def main(): gen = None pageTitle = [] for arg in wikipedia.handleArgs(): if arg.startswith('-start:'): start = arg[7:] gen = pagegenerators.AllpagesPageGenerator(start) else: pageTitle.append(arg) if pageTitle: pageTitle = ' '.join(pageTitle) page = wikipedia.Page(wikipedia.getSite(), pageTitle) gen = iter([page]) if...
site = insite.getSite(code = code) if site in ar: del ar[ar.index(site)] ar2 = ar2 + [site]
if code in getSite().family.langs: site = insite.getSite(code = code) if site in ar: del ar[ar.index(site)] ar2 = ar2 + [site]
def interwikiFormat(links, insite = None): """Create a suitable string encoding all interwiki links for a wikipedia page. 'links' should be a dictionary with the language names as keys, and either PageLink objects or the link-names of the pages as values. The string is formatted for inclusion in insite (defaulting to...
if site.category_on_one_line():
if Site(default_code).category_on_one_line():
def categoryFormat(links, insite = None): """Create a suitable string encoding all category links for a wikipedia page. 'links' should be a list of category pagelink objects. The string is formatted for inclusion in insite. """ if not links: return '' if insite is None: insite.getSite() s = [] for pl in links: s.appe...
return self.lang in self.family.category_on_one_line
return self.lang in config.category_on_one_line
def category_on_one_line(self): return self.lang in self.family.category_on_one_line
'zh-yue','zu',]
'zh-yue','zu',],
def __init__(self): family.Family.__init__(self) self.name = 'wikipedia'
login.storecookiedata(cookie, self.site, username)
login.storecookiedata(cookie, self.site, self.username)
def login(self, anonymous): """Initialises site and username data, or anonymous""" if anonymous: self.site = wikipedia.getSite(user=None) else: self.username = self.options.username or wikipedia.input(u"Username: ", encode=True) self.site = wikipedia.getSite(user=self.username) self.site._fill() # load cookies if not s...
@staticmethod
def handle_edit_conflict(self): fn = os.path.join(tempfile.gettempdir(), self.page) fp = open(fn, 'w') fp.write(new) fp.close() wikipedia.output(u"An edit conflict has arisen. Your edit has been saved to %s. Please try again." % fn)
hn = underline2space(self.hashname())
hn = self.hashname()
def get(self): """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:
'aa','ab','af','am','ang','ar','an','roa-rup','as','ast','av','ay',
'aa','ab','af','als','am','ang','ar','an','roa-rup','as','ast','av','ay',
def __init__(self):
'dv','dz','et','el','als','en','es','eo','eu','ee','fa','fo','fj','fr',
'dv','dz','et','el','en','es','eo','eu','ee','fa','fo','fj','fr',
def __init__(self):
if l.code() in ['zh-cn','zh-tw','zh'] and xpl.code() in ['zh-cn','zh-tw']:
if pl.code() in ['zh-cn','zh-tw','zh'] and xpl.code() in ['zh-cn','zh-tw']:
def reportBacklinks(self, new): """Report missing back links. This will be called from finish() if needed.""" for code in new.keys(): pl = new[code] if not unequal.bigger(self.inpl, pl): shouldlink = new.values() + [self.inpl] linked = pl.interwiki() for xpl in shouldlink: if xpl != pl and not xpl in linked: for l in l...
wikipedia.output(u"NOTE: Ignoring non-disambiguation page %s for %s because disambiguation page %s has already been found."%(pl.aslink(True),self.inpl.aslink(True),self.hasdisambig(pl.site())))
wikipedia.output(u"NOTE: Ignoring non-disambiguation page %s for %s because disambiguation page %s has already been found."%(pl.aslink(True),self.inpl.aslink(True),self.hasdisambig(pl.site()).aslink(True)))
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 ...
wikipedia.output(u"NOTE: Ignoring disambiguation page %s for %s because non-disambiguation page %s has already been found."%(pl.aslink(True),self.inpl.aslink(True),self.hasnondisambig(pl.site())))
wikipedia.output(u"NOTE: Ignoring disambiguation page %s for %s because non-disambiguation page %s has already been found."%(pl.aslink(True),self.inpl.aslink(True),self.hasnondisambig(pl.site()).aslink(True)))
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 ...
'en' : [u'disambig', u'tLAdisambig', u'disambiguation',u'2LCdisambig'],
'en' : [u'disambig', u'LND', u'2LA', u'TLAdisambig', u'disambiguation', u'2LCdisambig', u'4LA', u'acrocandis', u'hndis', u'numberdis', u'roadis'],
def __init__(self):
def ReadWarnfile(filename, sa):
def readWarnfile(filename, sa):
def ReadWarnfile(filename, sa): import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints hints = reader.getHints()[0] for pagename in hints.iterkeys(): pl = wikipedia.Page(wikipedia.getSite(), pagename) # The WarnfileReader gives us a list of pagelinks, but titletranslate.py expects a list ...
hints = reader.getHints()[0]
(hints, removeHints) = reader.getHints()
def ReadWarnfile(filename, sa): import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints hints = reader.getHints()[0] for pagename in hints.iterkeys(): pl = wikipedia.Page(wikipedia.getSite(), pagename) # The WarnfileReader gives us a list of pagelinks, but titletranslate.py expects a list ...
ReadWarnfile(arg[10:], sa)
warnfile = arg[10:]
def ReadWarnfile(filename, sa): import warnfile reader = warnfile.WarnfileReader(filename) # we won't use removeHints hints = reader.getHints()[0] for pagename in hints.iterkeys(): pl = wikipedia.Page(wikipedia.getSite(), pagename) # The WarnfileReader gives us a list of pagelinks, but titletranslate.py expects a list ...
choice=raw_input("? ")
choice=wikipedia.input("?")
def choosecats(pagetext): chosen=[] flag=False length=1000 print ("Give the new categories, one per line.") print ("Empty line: if the first, don't change. Otherwise: Ready.") print ("-: I made a mistake, let me start over.") print ("?: Give (more of) the text of the page.") print ("xx: if the first, remove all categor...
editR = re.compile('<li>.*?<a href=".*?" title=".*?">([^<]*)</a> <span class=\'user\'><a href=".*?" title=".*?">([^<]*?)</a></span>.*?(?:<span class=\'comment\'>(.*?)</span>)?</li>')
if self.site().version() < "1.4": editR = re.compile('<li>.*?<a href=".*?" title=".*?">([^<]*)</a> <span class=\'user\'><a href=".*?" title=".*?">([^<]*?)</a></span>.*?(?:<span class=\'comment\'>(.*?)</span>)?</li>') else: editR = re.compile('<li>.*?<a href=".*?" title=".*?">([^<]*)</a> <span class=\'history-user\'><a ...
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(self.site().language(), self.urlname())
s = categoryFormat(new, site = site)
s = categoryFormat(new, insite = site)
def replaceCategoryLinks(oldtext, new, site = None): """Replace the category links given in the wikitext given in oldtext by the new links given in new. 'new' should be a list of category pagelink objects. """ if site is None: site = getSite() # first remove interwiki links and add them later, so that # interwiki tags...
title = url2unicode(title, site = insite)
title = url2unicode(title, site = insite, site2 = site)
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...
line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.releasepid: if now - ptime <= self.dropdelay and pid != self.pid: count += 1 processes[pid] = ptime if pid >= my_pid: my_pid = pid+1
try: line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.releasepid: if now - ptime <= self.dropdelay and pid != self.pid: count += 1 processes[pid] = ptime if pid >= my_pid: my_pid = pid+1 except IndexError: pass
def checkMultiplicity(self): processes = {} my_pid = 1 count = 1 try: f = open('throttle.log','r') except IOError: if not self.pid: pass else: raise else: now = time.time() for line in f.readlines(): line = line.split(' ') pid = int(line[0]) ptime = int(line[1].split('.')[0]) if now - ptime <= self.releasepid: if now -...
def url2unicode(title, site): try: t = title.encode(site.encoding()) t = urllib.unquote(t) return unicode(t, site.encoding()) except UnicodeError: for enc in site.encodings(): try: t = title.encode(enc) t = urllib.unquote(t) return unicode(t, enc) except UnicodeError: pass raise
def url2unicode(title, site, site2 = None): encList = [site.encoding()] + list(site.encodings()) if site2 and site2 <> site: encList.append(site.encoding()) encList += list(site2.encodings()) firstException = None for enc in encList: try: t = title.encode(enc) t = urllib.unquote(t) return unicode(t, enc) except Unico...
def url2unicode(title, site): try: t = title.encode(site.encoding()) t = urllib.unquote(t) return unicode(t, site.encoding()) except UnicodeError: # try to handle all encodings (will probably retry utf-8) for enc in site.encodings(): try: t = title.encode(enc) t = urllib.unquote(t) return unicode(t, enc) except Unicode...
except wikipedia.isRedirectPage:
except wikipedia.IsRedirectPage:
def workon(page): try: text = page.get() except wikipedia.isRedirectPage: return # Here go edit text in whatever way you want. If you find you do not # want to edit this page, just return if text != page.get(): page.put(text) # Adding a summary text would be good
for arg in wikipedia.handleArgs: start.append(arg)
test = False for arg in wikipedia.handleArgs(): if arg.startswith("-test"): test = True else: start.append(arg)
def workon(page): try: text = page.get() except wikipedia.isRedirectPage: return # Here go edit text in whatever way you want. If you find you do not # want to edit this page, just return if text != page.get(): page.put(text) # Adding a summary text would be good
putPage(safetuple[0], safetuple[1], safetuple[2], comment=safetuple[3], watchArticle=safetuple[4], minorEdit=safetuple[5], newPage=safetuple[6], token=None,gettoken=True, sysop=safetuple[7])
self.putPage(safetuple[0], comment=safetuple[1], watchArticle=safetuple[2], minorEdit=safetuple[3], newPage=safetuple[4], token=None, gettoken=True, sysop=safetuple[5])
def putPage(self, text, comment = None, watchArticle = False, minorEdit = True, newPage = False, token = None, gettoken = False, sysop = False): """ Upload 'text' as new contents for this Page by filling out the edit page. Don't use this directly, use put() instead. """ safetuple = () # safetuple keeps the old value, ...
pagename = wikipedia.input('Which page to check:', encode = True)
pagename = wikipedia.input('Which page to check:')
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...
wikipedia.setAction(msg_redir[wikipedia.chooselang(wikipedia.mylang,msg_redir)]+': '+wrd)
wikipedia.setAction(msg_redir[wikipedia.chooselang(wikipedia.mylang,msg_redir)] + u': ' + wrd)
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...
wikipedia.setAction(msg[wikipedia.chooselang(wikipedia.mylang,msg)]+': '+wrd)
wikipedia.setAction(msg[wikipedia.chooselang(wikipedia.mylang,msg)] + u': ' + wrd)
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...
alternatives.append(str(thispl.getRedirectTo()))
target = str(thispl.getRedirectTo()) target = unicode(target, wikipedia.myencoding()) alternatives.append(target)
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...
wikipedia.output("%3d - %s" % (i, alternatives[i]), wikipedia.myencoding())
wikipedia.output("%3d - %s" % (i, alternatives[i]))
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...
templateName = self.template.title().split(':', 1)[1] templateRegex = re.compile('\{\{([mM][sS][gG]:)?[' + templateName[0].upper() + templateName[0].lower() + ']' + templateName[1:] + '}}')
templateName = self.template.titleWithoutNamespace() if wikipedia.getSite().nocapitalize: old = self.old else: templateName = '[' + templateName[0].upper() + templateName[0].lower() + ']' + templateName[1:] templateName = re.sub(' ', '[_ ]', templateName) templateRegex = re.compile(r'\{\{([mM][sS][gG]:)?' + templateNam...
def __iter__(self): import xmlreader mysite = wikipedia.getSite() dump = xmlreader.XmlDump(self.xmlfilename) # 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. templateName = self.template.title().sp...
if not wikipedia.getSite().nocapitalize:
if wikipedia.getSite().nocapitalize: old = self.old else:
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. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapit...
else: old = self.old
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. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapit...
templateR=re.compile(r'\{\{([mM][sS][gG]:)?' + old + '(?P<parameters>\|[^}]+|)}}')
templateRegex = re.compile(r'\{\{([mM][sS][gG]:)?' + old + '(?P<parameters>\|[^}]+|)}}')
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. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapit...