rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if "</noinclude>" in s2[firstafter:]: newtext = s2[:firstafter+1] + s + s2[firstafter+1:]
if "</noinclude>" in s2[firstafter:] and firstafter < 0: newtext = s2[:firstafter] + s + s2[firstafter:]
def replaceLanguageLinks(oldtext, new, site = None): """Replace the interwiki language links given in the wikitext given in oldtext by the new links given in new. 'new' should be a dictionary with the language names as keys, and Page objects as values. """ if site == None: site = getSite() s = interwikiFormat(new, ins...
return self.lang in self.site().family.category_on_one_line
return self.lang in self.family.category_on_one_line
def category_on_one_line(self): return self.lang in self.site().family.category_on_one_line
if regex:
if self.regex:
def read_pages_from_sql_dump(self): """ Generator which will yield PageLinks to pages that might contain text to replace. These pages will be retrieved from a local sql dump file (cur table). Arguments: * sqlfilename - the dump's path, either absolute or relative * replacements - a dictionary where old texts are keys...
filename = 'interwiki-graphs/%s.png' % inpl.urlname() graph.write(filename, prog = 'dot', format = 'png') wikipedia.output(u'Graph saved as %s' % filename)
filename = 'interwiki-graphs/%s-%s-%s.png' % (inpl.site().family.name, inpl.site().language(), inpl.urlname()) if graph.write(filename, prog = 'dot', format = 'png'): wikipedia.output(u'Graph saved as %s' % filename) else: wikipedia.output(u'Graph could not be saved as %s' % filename)
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') ...
wikipedia.output(u"WARNING: Page %s does no longer exist?!"%page)
wikipedia.output(u"WARNING: Page %s does no longer exist?!" % page.title())
def reportBacklinks(self, new, updatedSites): """ Report missing back links. This will be called from finish() if needed.
for i in range(len(line)):
for i in range(min(len(line), len(lastline))):
def showDiff(oldtext, newtext): """ Prints a string showing the differences between oldtext and newtext. The differences are highlighted (only on Unix systems) to show which changes were made. """ # For information on difflib, see http://pydoc.org/2.3/difflib.html color = { '+': 10, # green '-': 12 # red } diff = '' c...
del new[zh]
del new['zh']
def assemble(self): new = {} nerr = 0 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: self.problem("Found link to %s"%pl.asasciilink()) for pl2 in self.foundin[pl]: print " ",pl2.asasciilink() nerr += 1 eli...
print "DBG> successfulupload contains %s" % get('successfulupload')
print "DBG> successfulupload contains %s" % get('successfulupload') print "DBG> deletedtext contains %s" % get('deletedtext')
def main(): debug = False refresh_all = False for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg) if arg: if arg == '-debug': debug = True elif arg == '-all': refresh_all = True if refresh_all: refresh_all_messages() else: refresh_messages(wikipedia.getSite()) if debug: print "DBG> successfulupload contains %s" %...
print data
def putPage(site, name, text, comment = None, watchArticle = False, minorEdit = True, newPage = False, anon=False, token = None): """Upload 'text' on page 'name' to the 'site' wiki. Use of this routine can normally be avoided; use PageLink.put instead. """ # Check whether we are not too quickly after the previous putPa...
elif not site.gettoken:
elif not site.gettoken():
def getPage(site, name, get_edit_page = True, read_only = False, do_quote = True, get_redirect=False): """ 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 PageLink object instead. Arguments: site - the wiki site name - the p...
titleLength = len(titleWithSection) titleWithSection = titleWithSection.rstrip() hadTrailingSpaces = (len(titleWithSection) != titleLength)
if not trailingChars or label: titleLength = len(titleWithSection) titleWithSection = titleWithSection.rstrip() hadTrailingSpaces = (len(titleWithSection) != titleLength)
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...
label = m.group('label')
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...
labelLength = len(label) label = label.rstrip() hadTrailingSpaces = (len(label) != label)
if not trailingChars: labelLength = len(label) label = label.rstrip() hadTrailingSpaces = (len(label) != labelLength)
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...
label = titleWithSection trailingChars = m.group('linktrail') if trailingChars and not hadTrailingSpaces:
label = titleWithSection if 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...
if trailingChars: newLink += 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...
second is a predicate function with an integer parameter that returns true or false if the 1st function applies or not.
second is a predicate function with an integer parameter that returns true or false. When the 2nd function evaluates to true, the 1st function is used.
def multi( value, tuplst ): """This method is used when different patterns are used for the same entry. Example: 1st century, 2nd century, etc. The tuplst is a list of tupples. Each tupple must contain two functions: first to encode/decode a single value (e.g. simpleInt), second is a predicate function with an integer ...
return dh_constVal( value, 0, match ) def dh_constVal( value, ind, match ): """This function helps with matching a single value to a constant. formats['CurrEvents']['en'](ind) => u'Current Events' formats['CurrEvents']['en'](u'Current Events') => ind"""
def dh_singVal( value, match ): """This function helps with matching a single value. formats['CurrEvents']['en'](0) => u'Current Events' formats['CurrEvents']['en'](u'Current Events') => 0""" if type(value) is int: if value == 0: return match else: raise ValueError("unknown value %d" % value) else: if value == match: r...
if value == 0:
if value == ind:
def dh_singVal( value, match ): """This function helps with matching a single value. formats['CurrEvents']['en'](0) => u'Current Events' formats['CurrEvents']['en'](u'Current Events') => 0""" if type(value) is int: if value == 0: return match else: raise ValueError("unknown value %d" % value) else: if value == match: r...
return 0
return ind
def dh_singVal( value, match ): """This function helps with matching a single value. formats['CurrEvents']['en'](0) => u'Current Events' formats['CurrEvents']['en'](u'Current Events') => 0""" if type(value) is int: if value == 0: return match else: raise ValueError("unknown value %d" % value) else: if value == match: r...
return unicode(value).translate(_knDigitsToLocal)
return unicode(value).translate(digitsToLocal)
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...
tmp = value.translate(_knDigitsToLocal)
tmp = value.translate(digitsToLocal)
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...
tmp = value.translate(_knLocalToDigits)
tmp = value.translate(localToDigits)
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...
'ca' : lambda v: dh_dec( v, u'Dècada del %d' ),
'ca' : lambda v: multi( v, [ (lambda x: dh_dec( x, u'Dècada de %d' ), lambda p: p == 1970), (lambda x: dh_dec( x, u'Dècada del %d' ), alwaysTrue)]),
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...
'fi' : lambda v: dh_dec( v, u'%d-luku' ),
'fi' : lambda v: multi( v, [ (lambda x: dh_dec( x, u'%d-luku' ), lambda p: (p % 100 != 0)), (lambda x: dh_dec( x, u'%d-vuosikymmen' ), alwaysTrue)]),
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...
'hr' : lambda v: dh( v, u'%d-%d', lambda i: (encDec0(i),encDec0(i)+9), lambda v: v[0] ), 'hu' : lambda v: dh_dec( v, u'%d-as évek' ),
'hr' : lambda v: dh( v, u'%d-%d', lambda i: (encDec0(i),encDec0(i)+9), lambda ii: ii[0] ), 'hu' : lambda v: multi( v, [ (lambda x: dh_dec( x, u'%d-ás évek' ), lambda p: p == 0), (lambda x: dh_dec( x, u'%d-as évek' ), lambda p: (p % 100 / 10) in [0,2,3,6,8]), (lambda x: dh_dec( x, u'%d-es év...
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...
'is' : lambda v: dh( v, u'%d–%d', lambda i: (encDec1(i),encDec1(i)+9), lambda v: v[0]-1 ),
'is' : lambda v: dh( v, u'%d–%d', lambda i: (encDec1(i),encDec1(i)+9), lambda ii: ii[0]-1 ),
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...
(lambda x: dh_dec( v, u'%d-talet (decennium)' ), lambda x: (x % 100 == 0)), (lambda x: dh_dec( v, u'%d-talet' ), alwaysTrue)]),
(lambda x: dh_dec( x, u'%d-talet (decennium)' ), lambda p: (p % 100 == 0)), (lambda x: dh_dec( x, u'%d-talet' ), alwaysTrue)]),
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...
(lambda x: dh_dec( x, u'%d-ві' ), lambda x: x == 0 or (x % 100 == 40)), (lambda x: dh_dec( x, u'%d-ні' ), lambda x: x % 1000 == 0),
(lambda x: dh_dec( x, u'%d-ві' ), lambda p: p == 0 or (p % 100 == 40)), (lambda x: dh_dec( x, u'%d-ні' ), lambda p: p % 1000 == 0),
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...
(lambda x: dh_dec( v, u'%d-talet f.Kr. (decennium)' ), lambda x: (x % 100 == 0)), (lambda x: dh_dec( v, u'%d-talet f.Kr.' ), alwaysTrue)]),
(lambda x: dh_dec( x, u'%d-talet f.Kr. (decennium)' ), lambda p: (p % 100 == 0)), (lambda x: dh_dec( x, u'%d-talet f.Kr.' ), alwaysTrue)]),
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...
(lambda x: dh_dec( x, u'%d-ві до Р.Х.' ), lambda x: x == 0 or (x % 100 == 40)),
(lambda x: dh_dec( x, u'%d-ві до Р.Х.' ), lambda p: p == 0 or (p % 100 == 40)),
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...
(lambda x: dh_noConv( v, u'%dste eeu' ), lambda x: x in [1,8] or (x >= 20)), (lambda x: dh_noConv( x, u'%dde eeu' ), alwaysTrue)]),
(lambda x: dh_noConv( x, u'%dste eeu' ), lambda p: p in [1,8] or (p >= 20)), (lambda x: dh_noConv( x, u'%dde eeu' ), alwaysTrue)]), 'als': lambda v: dh_noConv( v, u'%d. Jahrhundert' ),
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...
(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_noConv( x, u'%dst century' ), lambda p: p == 1 or (p > 20 and p%10 == 1)), (lambda x: dh_noConv( x, u'%dnd century' ), lambda p: p == 2 or (p > 20 and p%10 == 2)), (lambda x: dh_noConv( x, u'%drd century' ), lambda p: p == 3 or (p > 20 and p%10 == 3)),
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...
'fi' : lambda v: dh( v, u'%d00-luku', lambda i: i-1, lambda v: v[0]+1 ),
'en' : lambda v: multi( v, [ (lambda x: dh_constVal( x, 20, u'سده ۲۰ (میلادی)'), lambda p: p == 20)]), 'fi' : lambda v: dh( v, u'%d00-luku', lambda i: i-1, lambda ii: ii[0]+1 ),
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...
(lambda x: dh_noConv( v, u'%dsa kansblydhen' ), lambda x: x <= 3), (lambda x: dh_noConv( v, u'%da kansblydhen' ), lambda x: x == 4), (lambda x: dh_noConv( v, u'%des kansblydhen' ), lambda x: x == 5), (lambda x: dh_noConv( v, u'%dns kansblydhen' ), lambda x: x >= 20), (lambda x: dh_noConv( v, u'%dves kansblydhen' ), alw...
(lambda x: dh_noConv( x, u'%dsa kansblydhen' ), lambda p: p <= 3), (lambda x: dh_noConv( x, u'%da kansblydhen' ), lambda p: p == 4), (lambda x: dh_noConv( x, u'%des kansblydhen' ), lambda p: p == 5), (lambda x: dh_noConv( x, u'%dns kansblydhen' ), lambda p: p >= 20), (lambda x: dh_noConv( x, u'%dves kansblydhen' )...
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...
'li' : lambda v: slh( v, [u'Ierste iew', u'Twiede iew', u'Derde iew', u'Veerde iew', u'Viefde iew', u'Zesde iew', u'Zevende iew', u'Achste iew', u'Negende iew', u'Tiende iew', u'Elfde iew', u'Twelfde iew', u'Dertiende iew', u'Veertiende iew', u'Vieftiende iew', u'Zestiende iew', u'Zeventiende iew', u'Achtiende iew...
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...
'nn' : lambda v: dh( v, u'%d00-talet', lambda i: i-1, lambda v: v[0]+1 ),
'nn' : lambda v: dh( v, u'%d00-talet', lambda i: i-1, lambda ii: ii[0]+1 ),
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...
'sv' : lambda v: dh( v, u'%d00-talet', lambda i: i-1, lambda v: v[0]+1 ),
'sv' : lambda v: dh( v, u'%d00-talet', lambda i: i-1, lambda ii: ii[0]+1 ),
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...
'sv' : lambda v: dh( v, u'%d00-talet f.Kr.', lambda i: i-1, lambda v: v[0]+1 ),
'sv' : lambda v: dh( v, u'%d00-talet f.Kr.', lambda i: i-1, lambda ii: ii[0]+1 ),
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...
(lambda x: dh_noConv( x, u'%dst millennium' ), lambda x: x == 1 or (x > 20 and x%10 == 1)), (lambda x: dh_noConv( x, u'%dnd millennium' ), lambda x: x == 2 or (x > 20 and x%10 == 2)), (lambda x: dh_noConv( x, u'%drd millennium' ), lambda x: x == 3 or (x > 20 and x%10 == 3)),
(lambda x: dh_noConv( x, u'%dst millennium' ), lambda p: p == 1 or (p > 20 and p%10 == 1)), (lambda x: dh_noConv( x, u'%dnd millennium' ), lambda p: p == 2 or (p > 20 and p%10 == 2)), (lambda x: dh_noConv( x, u'%drd millennium' ), lambda p: p == 3 or (p > 20 and p%10 == 3)),
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...
(lambda x: dh_roman( x, u'%ser millénaire' ), lambda x: x == 1), (lambda x: dh_roman( v, u'%se millénaire' ), alwaysTrue)]),
(lambda x: dh_roman( x, u'%ser millénaire' ), lambda p: p == 1), (lambda x: dh_roman( x, u'%se millénaire' ), alwaysTrue)]),
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...
'ro' : lambda v: dh_roman( v, u'Mileniul %s' ),
'pt' : lambda v: slh( v, [u'Primeiro milénio d.C.', u'Segundo milénio d.C.', u'Terceiro milénio d.C.', u'Quarto milénio d.C.'] ), 'ro' : lambda v: slh( v, [u'Mileniul I', u'Mileniul al II-lea'] ),
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...
'sv' : lambda v: dh( v, u'%d000-talet (millennium)', lambda i: i-1, lambda v: v[0]+1 ),
'sv' : lambda v: dh( v, u'%d000-talet (millennium)', lambda i: i-1, lambda ii: ii[0]+1 ),
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...
'pt' : lambda v: slh( v, [u'Primeiro milénio a.C.', u'Segundo milénio a.C.', u'Terceiro milénio a.C.', u'Quarto milénio a.C.'] ),
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...
'sv' : lambda v: dh( v, u'%d000-talet f.Kr. (millennium)', lambda i: i-1, lambda v: v[0]+1 ),
'sv' : lambda v: dh( v, u'%d000-talet f.Kr. (millennium)', lambda i: i-1, lambda ii: ii[0]+1 ),
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...
u'(lambda x: dh_noConv( x, u"%%dî d\' %s" ), lambda x: x == 1),' + u'(lambda x: dh_noConv( x, u"%%d d\' %s" ), lambda x: x in [2,3,20,22,23]),' + u'(lambda x: dh_noConv( x, u"%%d di %s" ), alwaysTrue)])') % (waMonthNames[i],waMonthNames[i],waMonthNames[i]))
u'(lambda x: dh_noConv( x, u"%%dî d\' %s" ), lambda p: p == 1),' + u'(lambda x: dh_noConv( x, u"%%d d\' %s" ), lambda p: p in [2,3,20,22,23]),' + u'(lambda x: dh_noConv( x, u"%%d di %s" ), alwaysTrue)])') % (waMonthNames[i],waMonthNames[i],waMonthNames[i]))
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...
u'(lambda x: dh_noConv( x, u"%%dî d\' %s" ), lambda x: x == 1),' + u'(lambda x: dh_noConv( x, u"%%d d\' %s" ), alwaysTrue)])') % (waMonthNames[i],waMonthNames[i]))
u'(lambda x: dh_noConv( x, u"%%dî d\' %s" ), lambda p: p == 1),' + u'(lambda x: dh_noConv( x, u"%%d d\' %s" ), alwaysTrue)])') % (waMonthNames[i],waMonthNames[i]))
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...
wikipedia.output(u'Page [[%s]] does not seem to exist?! Skipping.') % refpl.linkname()
wikipedia.output(u'Page [[%s]] does not seem to exist?! Skipping.' % refpl.linkname())
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 response.status == 302:
if response.status in [200, 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. """ # Get file contents if '://' in self...
wikipedia.output('%i %s' % (response.status, response.reason))
wikipedia.output(u'%i %s' % (response.status, response.reason))
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. """ # Get file contents if '://' in self...
return "*" + pl.aslink()
return "*" + pl.aslink(othersite = None)
def formatPl(self, pl): if hasattr(pl, '_contents'): #TODO: UGLY! need pl.isLoaded() if pl.isDisambig(): return "*" + pl.aslink() else: return pl.aslink() else: return "?" + pl.aslink()
return pl.aslink()
return pl.aslink(othersite = None)
def formatPl(self, pl): if hasattr(pl, '_contents'): #TODO: UGLY! need pl.isLoaded() if pl.isDisambig(): return "*" + pl.aslink() else: return pl.aslink() else: return "?" + pl.aslink()
return "?" + pl.aslink()
return "?" + pl.aslink(othersite = None)
def formatPl(self, pl): if hasattr(pl, '_contents'): #TODO: UGLY! need pl.isLoaded() if pl.isDisambig(): return "*" + pl.aslink() else: return pl.aslink() else: return "?" + pl.aslink()
R = re.compile(r'\[\[\s*(?P<namespace>%s)\s*:(?P<catName>.+?)(?:\|(?P<sortKey>.+?)\]\])' % catNamespace)
R = re.compile(r'\[\[\s*(?P<namespace>%s)\s*:(?P<catName>.+?)(?:\|(?P<sortKey>.+?))?\]\]' % catNamespace)
def getCategoryLinks(text, site): import catlib """Returns a list of category links. in the form {code:pagename}. Do not call this routine directly, use Page objects instead""" result = [] # Ignore interwiki links within nowiki tags and HTML comments nowikiOrHtmlCommentR = re.compile(r'<nowiki>.*?</nowiki>|<!--.*?-->',...
if file_age > 7 * 24 * 60 * 60:
if file_age > 30 * 24 * 60 * 60:
def get(key): try: # find out how old our saved dump is (in seconds) file_age = time.time() - os.path.getmtime('mediawiki-messages/mediawiki-messages-%s.dat' % wikipedia.mylang) # if it's older than 7 days, reload it if file_age > 7 * 24 * 60 * 60: print 'Current MediaWiki message dump is outdated, reloading' refresh_m...
+ "<a href=.+? 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') #allmess...
get('about')
debug = True
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') #allmess...
if debug: print get('successfulupload')
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') #allmess...
splitTitle = title.split(':')
title = title.split(':')
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...
if len(splitTitle) > 1:
if len(title) > 1:
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...
if splitTitle[0] == site.family.namespace('_default', ns): splitTitle[0] = site.namespace(ns)
if title[0] == site.family.namespace('_default', ns): title[0] = site.namespace(ns)
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...
print title print pl print self.pages
print repr(title) print repr(pl) print repr(self.pages)
def oneDone(self, title, timestamp, text): #print "DBG>", repr(title), timestamp, len(text) pl = PageLink(self.code, title) for pl2 in self.pages: #print "DBG>", pl, pl2, pl2.hashfreeLinkname() if PageLink(self.code, pl2.hashfreeLinkname()) == pl: if not hasattr(pl2,'_contents') and not hasattr(pl2,'_getexception'): br...
addr = self.addr%special[self.code]
try: addr = self.addr%special[self.code] except KeyError: print "BUG: Can not find name of Special in %s:" % self.code raise
def getData(self): import httplib addr = self.addr%special[self.code] pagenames = u'\r\n'.join([x.hashfreeLinkname() for x in self.pages]) data = urlencode(( ('action', 'submit'), ('pages', pagenames), ('curonly', 'True'), )) headers = {"Content-type": "application/x-www-form-urlencoded", "User-agent": "RobHooftWikiRob...
def __init__(self,lang,term,relatedwords=[],label=''):
def __init__(self,lang,term,relatedwords=[]):
def __init__(self,lang,term,relatedwords=[],label=''): """ Constructor Generally called with two parameters: - The language of the term - The term (string)
self.label=label
def __init__(self,lang,term,relatedwords=[],label=''): """ Constructor Generally called with two parameters: - The language of the term - The term (string)
def setLabel(self,label): self.label=label.replace('<!--','').replace('-->','') def getLabel(self): if self.label: return '<!--' + self.label + '-->'
def setLabel(self,label): self.label=label.replace('<!--','').replace('-->','')
and read it into our object structure'''
and read it into our object structure. It returns a list of dictionaries. Each dictionary contains a header object and the textual content found under that header. Only relevant content is stored. Empty lines and lines to create tables for presentation to the user are taken out.'''
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if len(line) <2: continue
if len(line) <2: templist.append(line) continue
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
print "tempdictstructure: ", tempdictstructure print "splitcontent: ",splitcontent
print "splitcontent: ",splitcontent,"\n\n"
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
print line
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
print "templist: ", templist raw_input("") """ if header.type==u'pos': if line[:2] == "'''":
for contentblock in splitcontent: print "contentblock:",contentblock print contentblock['header'] if contentblock['header'].type==u'pos': flag=False for line in contentblock['text']: print line print line[:3] if line[:3] == "'''":
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if part[:2] == "'''":
print part[:3], "Flag:", flag if flag==False and part[:3] == "'''":
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if part[:1].lower()=='pl':
if part.replace("'",'')[:2].lower()=='pl':
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if part[:2].lower()=='dim':
if part.replace("'",'')[:3].lower()=='dim':
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
plural=part.replace(',','').strip()
plural=part.replace(',','').replace("'",'').strip() print 'Plural: ',plural
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
diminutive=part.replace(',','').strip()
diminutive=part.replace(',','').replace("'",'').strip() print 'Diminutive: ',diminutive
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if line[:1] == "{{":
if line[:2] == "{{":
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if line[:0] == "
if line[:1] == "
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
label=line[pos+4,pos2]
label=line[pos+4:pos2]
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
print label
print 'label:',label
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
if line[:1] == "
if line[:2] == "
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
"""
raw_input("")
def parseWikiPage(ofn,wikilang,pagetopic): '''This function will parse the content of a Wiktionary page and read it into our object structure''' apage = WiktionaryPage(wikilang,pagetopic) templist = [] context = {} content = open(ofn).readlines() splitcontent=[] for line in content: # Let's get rid of line breaks an...
return html2unicode(s, language = incode)
return unicodeName(s, language = incode)
def interwikiFormat(links, incode): """Create a suitable string to start a wikipedia page consisting of interwikilinks given as a dictionary of code:pagename in the argument. """ s = [] ar = links.keys() ar.sort() if mylang in config.interwiki_englishfirst: if 'en' in ar: del ar[ar.index('en')] ar[:0]=['en'] for code i...
True if the page except for language links and category links has less than 4 characters, False otherwise. Can raise the same exceptions as get()
True if the page has less than 4 characters, except for language links and category links, False otherwise. Can raise the same exceptions as get()
def isEmpty(self): """ True if the page except for language links and category links has less than 4 characters, False otherwise. Can raise the same exceptions as get() """ txt = self.get() txt = removeLanguageLinks(txt) txt = removeCategoryLinks(txt, site = self.site()) if len(txt) < 4: return True else: return False
def getReferences(self, follow_redirects = True, offset = 0): """ Returns a list of pages that link to the page.
def getReferences(self, follow_redirects=True, offset=0): """ Return a list of pages that link to the page.
def isDisambig(self): defdis = self.site().family.disambig( "_default" ) locdis = self.site().family.disambig( self._site.lang )
txt = site.getUrl(path) txt = txt.replace('<a', 'a') txt = txt.replace('</a', '/a') txt = txt.replace('<li', 'li') txt = txt.replace('</li', 'li') if not follow_redirects: cascadedListR = re.compile(r"(.*<ul>[^<]*)<ul>[^<]*<\/ul>([^<]*</\ul>.*)") pos = 0 while cascadedListR.search(txt): m = cascadedListR.search(tx...
delay = 1 while True: txt = site.getUrl(path) startmarker = u"<!-- start content -->" endmarker = u"<!-- end content -->" try: start = txt.index(startmarker) + len(startmarker) end = txt.index(endmarker) except ValueError: output( u"Invalid page received from server.... Retrying in %i minutes." % delay) time.sleep(...
def getReferences(self, follow_redirects = True, offset = 0): """ Returns a list of pages that link to the page. If follow_redirects is True, also returns pages that link to a redirect pointing to the page. If offset is non-zero, skips that many references before loading. """ site = self.site() path = site.references_a...
if page not in refPages: refPages.append(page)
if refTitle in redirTitles: page._redirarg = self.title() refPages.append(page)
def getReferences(self, follow_redirects = True, offset = 0): """ Returns a list of pages that link to the page. If follow_redirects is True, also returns pages that link to a redirect pointing to the page. If offset is non-zero, skips that many references before loading. """ site = self.site() path = site.references_a...
def exceptionApplies(self, original_text): """ Returns True iff one of the exceptions applies for the given text.
def checkExceptions(self, original_text): """ If one of the exceptions applies for the given text, returns the substring. which matches the exception. Otherwise it returns None.
def exceptionApplies(self, original_text): """ Returns True iff one of the exceptions applies for the given text. """ for exception in self.exceptions: if self.regex: exception = re.compile(exception) hit = exception.search(original_text) if hit: wikipedia.output(u'Skipping %s because it contains %s' % (pl.linkname(), ...
wikipedia.output(u'Skipping %s because it contains %s' % (pl.linkname(), hit.group(0))) return True
return hit.group(0)
def exceptionApplies(self, original_text): """ Returns True iff one of the exceptions applies for the given text. """ for exception in self.exceptions: if self.regex: exception = re.compile(exception) hit = exception.search(original_text) if hit: wikipedia.output(u'Skipping %s because it contains %s' % (pl.linkname(), ...
wikipedia.output(u'Skipping %s because it contains %s' % (pl.linkname(), original_text[hit:hit + len(exception)])) return True return False
return original_text[hit:hit + len(exception)] return None
def exceptionApplies(self, original_text): """ Returns True iff one of the exceptions applies for the given text. """ for exception in self.exceptions: if self.regex: exception = re.compile(exception) hit = exception.search(original_text) if hit: wikipedia.output(u'Skipping %s because it contains %s' % (pl.linkname(), ...
match = self.checkExceptions(original_text)
def run(self): """ Starts the robot. """ # Run the generator which will yield PageLinks to pages which might need to be # changed. for pl in self.generator.generate(): print '' try: # Load the page's text from the wiki original_text = pl.get() except wikipedia.NoPage: wikipedia.output(u'Page %s not found' % pl.linkname...
if not self.exceptionApplies(original_text):
if match: wikipedia.output(u'Skipping %s because it contains %s' % (pl.linkname(), match)) else:
def run(self): """ Starts the robot. """ # Run the generator which will yield PageLinks to pages which might need to be # changed. for pl in self.generator.generate(): print '' try: # Load the page's text from the wiki original_text = pl.get() except wikipedia.NoPage: wikipedia.output(u'Page %s not found' % pl.linkname...
result[code] = m.group(1)
if m.group(1): result[code] = m.group(1) else: print "ERROR: empty link to %s:"%(code)
def getLanguageLinks(text): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}""" result = {} for code in langs: m=re.search(r'\[\['+code+':([^\]]*)\]\]', text) if m: result[code] = m.group(1) return result
title = title.split(':')
splitTitle = title.split(':')
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...
if len(title) > 1:
if len(splitTitle) > 1:
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...
if title[0] == site.family.namespace('_default',ns): title[0] = site.namespace(ns) title = ':'.join(title)
if splitTitle[0] == site.family.namespace('_default', ns): splitTitle[0] = site.namespace(ns)
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...
print e
wikipedia.output(u'%s' % e)
def run(self): commons = wikipedia.Site('commons', 'commons') comment = wikipedia.translate(self.site, nowCommonsMessage) for page in self.getPageGenerator(): wikipedia.output(u'\n\n>> %s <<\n' % page.title()) try: localImagePage = wikipedia.ImagePage(self.site, page.title()) if localImagePage.fileIsOnCommons(): wikipe...
if search: index = text.lower().index(search.lower()) line = text[:index].count('\n') column = index - (text[:index].rfind('\n') + 1) else: line = column = 0
def edit(self, text, search = None): """ Calls the editor and thus allows the user to change the text. Returns the modified text. Halts the thread's operation until the editor is closed. Returns None if the user didn't save the text file in his text editor. """ if config.editor: tempFilename = '%s.%s' % (tempfile.mkte...
lineOfFirstOccurence = text[:text.index(search)].count('\n') command += " -l %i" % lineOfFirstOccurence
command += " -l %i -c %i" % (line, column)
def edit(self, text, search = None): """ Calls the editor and thus allows the user to change the text. Returns the modified text. Halts the thread's operation until the editor is closed. Returns None if the user didn't save the text file in his text editor. """ if config.editor: tempFilename = '%s.%s' % (tempfile.mkte...
lineOfFirstOccurence = text[:text.index(search)].count('\n') + 1 command += " +line:%i" % lineOfFirstOccurence
lineOfFirstOccurence += 1 command += " +line:%i" % line
def edit(self, text, search = None): """ Calls the editor and thus allows the user to change the text. Returns the modified text. Halts the thread's operation until the editor is closed. Returns None if the user didn't save the text file in his text editor. """ if config.editor: tempFilename = '%s.%s' % (tempfile.mkte...
def initialise_data(self): """Set editor, page and pagelink attributes""" self.setpage()
def __init__(self, args): """Takes one argument, usually this is sys.argv[1:]""" self.all_args = args self.set_options() self.site = wikipedia.getSite()