本文整理汇总了Python中wikipedia.replaceCategoryLinks函数的典型用法代码示例。如果您正苦于以下问题:Python replaceCategoryLinks函数的具体用法?Python replaceCategoryLinks怎么用?Python replaceCategoryLinks使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了replaceCategoryLinks函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: treat
def treat(self, page):
text = self.load(page)
if text is None:
return
cats = page.categories()
# Show the title of the page we're working on.
# Highlight the title in purple.
pywikibot.output(
u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
% page.title())
pywikibot.output(u"Current categories:")
for cat in cats:
pywikibot.output(u"* %s" % cat.title())
catpl = pywikibot.Page(self.site, self.newcatTitle, defaultNamespace=14)
if catpl in cats:
pywikibot.output(u"%s is already in %s."
% (page.title(), catpl.title()))
else:
if self.sort:
catpl = self.sorted_by_last_name(catpl, page)
pywikibot.output(u'Adding %s' % catpl.title(asLink=True))
cats.append(catpl)
text = pywikibot.replaceCategoryLinks(text, cats)
if not self.save(text, page, self.editSummary):
pywikibot.output(u'Page %s not saved.'
% page.title(asLink=True))
示例2: make_categories
def make_categories(page, list, site=None):
if site is None:
site = wikipedia.getSite()
pllist = []
for p in list:
cattitle = "%s:%s" % (site.category_namespace(), p)
pllist.append(wikipedia.Page(site, cattitle))
page.put_async(wikipedia.replaceCategoryLinks(page.get(), pllist), comment=wikipedia.translate(site.lang, msg))
示例3: make_categories
def make_categories(page, list, site = None):
if site is None:
site = pywikibot.getSite()
pllist=[]
for p in list:
cattitle="%s:%s" % (site.category_namespace(), p)
pllist.append(pywikibot.Page(site,cattitle))
page.put_async(pywikibot.replaceCategoryLinks(page.get(), pllist),
comment=i18n.twtranslate(site.lang, 'catall-changing'))
示例4: categories
def categories(self):
for page in self.generator:
try:
pywikibot.output(u'\n>>>> %s <<<<' % page.title())
commons = pywikibot.getSite().image_repository()
commonsCategory = catlib.Category(commons,
'Category:%s' % page.title())
try:
getcommonscat = commonsCategory.get(get_redirect=True)
commonsCategoryTitle = commonsCategory.title()
categoryname = commonsCategoryTitle.split('Category:', 1)[1]
if page.title() == categoryname:
oldText = page.get()
text = oldText
# for commonscat template
findTemplate = re.compile(ur'\{\{[Cc]ommons')
s = findTemplate.search(text)
findTemplate2 = re.compile(ur'\{\{[Ss]isterlinks')
s2 = findTemplate2.search(text)
if s or s2:
pywikibot.output(u'** Already done.')
else:
text = pywikibot.replaceCategoryLinks(
text + u'{{commonscat|%s}}' % categoryname,
page.categories())
if oldText != text:
pywikibot.showDiff(oldText, text)
if not self.acceptall:
choice = pywikibot.inputChoice(
u'Do you want to accept these changes?',
['Yes', 'No', 'All'], ['y', 'N', 'a'],
'N')
if choice == 'a':
self.acceptall = True
if self.acceptall or choice == 'y':
try:
msg = pywikibot.translate(
pywikibot.getSite(), comment2)
page.put(text, msg)
except pywikibot.EditConflict:
pywikibot.output(
u'Skipping %s because of edit '
u'conflict'
% (page.title()))
except pywikibot.NoPage:
pywikibot.output(u'Category does not exist in Commons!')
except pywikibot.NoPage:
pywikibot.output(u'Page %s does not exist' % page.title())
except pywikibot.IsRedirectPage:
pywikibot.output(u'Page %s is a redirect; skipping.'
% page.title())
except pywikibot.LockedPage:
pywikibot.output(u'Page %s is locked' % page.title())
示例5: putAfterTemplate
def putAfterTemplate (page, template, toadd, loose=True):
'''
Try to put text after template.
If the template is not found return False if loose is set to False
If loose is set to True: Remove interwiki's, categories, add template, restore categories, restore interwiki's.
Based on cc-by-sa-3.0 code by Dschwen
'''
oldtext = page.get()
newtext = u''
templatePosition = oldtext.find(u'{{%s' % (template,))
if templatePosition >= 0:
previousChar = u''
currentChar = u''
templatePosition += 2
curly = 1
square = 0
while templatePosition < len(oldtext):
currentChar = oldtext[templatePosition]
if currentChar == u'[' and previousChar == u'[' :
square += 1
previousChar = u''
if currentChar == u']' and previousChar == u']' :
square -= 1
previousChar = u''
if currentChar == u'{' and previousChar == u'{' :
curly += 1
previousChar = u''
if currentChar == u'}' and previousChar == u'}' :
curly -= 1
previousChar = u''
previousChar = currentChar
templatePosition +=1
if curly == 0 and square <= 0 :
# Found end of template
break
newtext = oldtext[:templatePosition] + u'\n' + toadd + oldtext[templatePosition:]
else:
if loose:
newtext = oldtext
cats = wikipedia.getCategoryLinks(newtext)
ll = wikipedia.getLanguageLinks(newtext)
nextext = wikipedia.removeLanguageLinks (newtext)
newtext = wikipedia.removeCategoryLinks(newtext)
newtext = newtext + u'\n' + toadd
newtext = wikipedia.replaceCategoryLinks(newtext, cats)
newtext = wikipedia.replaceLanguageLinks(newtext, ll)
return newtext
示例6: standardizeCategories
def standardizeCategories(self, text):
"""
Makes sure that categories are put to the correct position, but
does not sort them.
"""
# The PyWikipediaBot is no longer allowed to touch categories on the German Wikipedia. See http://de.wikipedia.org/wiki/Hilfe_Diskussion:Personendaten/Archiv/bis_2006#Position_der_Personendaten_am_.22Artikelende.22
if self.site != wikipedia.getSite('de', 'wikipedia'):
categories = wikipedia.getCategoryLinks(text, site = self.site)
text = wikipedia.replaceCategoryLinks(text, categories, site = self.site)
return text
示例7: categories
def categories(self):
for page in self.generator:
try:
wikipedia.output(u"\n>>>> %s <<<<" % page.title())
getCommons = wikipedia.getSite("commons", "commons")
commonsCategory = catlib.Category(getCommons, "Category:%s" % page.title())
try:
getcommonscat = commonsCategory.get(get_redirect=True)
commonsCategoryTitle = commonsCategory.title()
categoryname = commonsCategoryTitle.split("Category:", 1)[1]
if page.title() == categoryname:
oldText = page.get()
text = oldText
# for commonscat template
findTemplate = re.compile(ur"\{\{[Cc]ommons")
s = findTemplate.search(text)
findTemplate2 = re.compile(ur"\{\{[Ss]isterlinks")
s2 = findTemplate2.search(text)
if s or s2:
wikipedia.output(u"** Already done.")
else:
text = wikipedia.replaceCategoryLinks(
text + u"{{commonscat|%s}}" % categoryname, page.categories()
)
if oldText != text:
wikipedia.showDiff(oldText, text)
if not self.acceptall:
choice = wikipedia.inputChoice(
u"Do you want to accept these changes?",
["Yes", "No", "All"],
["y", "N", "a"],
"N",
)
if choice == "a":
self.acceptall = True
if self.acceptall or choice == "y":
try:
msg = wikipedia.translate(wikipedia.getSite(), comment2)
page.put(text, msg)
except wikipedia.EditConflict:
wikipedia.output(u"Skipping %s because of edit conflict" % (page.title()))
except wikipedia.NoPage:
wikipedia.output(u"Category does not exist in Commons!")
except wikipedia.NoPage:
wikipedia.output(u"Page %s does not exist?!" % page.title())
except wikipedia.IsRedirectPage:
wikipedia.output(u"Page %s is a redirect; skipping." % page.title())
except wikipedia.LockedPage:
wikipedia.output(u"Page %s is locked?!" % page.title())
示例8: pages
def pages(self):
for page in self.generator:
try:
pywikibot.output(u"\n>>>> %s <<<<" % page.title())
commons = pywikibot.getSite().image_repository()
commonspage = pywikibot.Page(commons, page.title())
try:
getcommons = commonspage.get(get_redirect=True)
if page.title() == commonspage.title():
oldText = page.get()
text = oldText
# for commons template
findTemplate = re.compile(ur"\{\{[Cc]ommonscat")
s = findTemplate.search(text)
findTemplate2 = re.compile(ur"\{\{[Ss]isterlinks")
s2 = findTemplate2.search(text)
if s or s2:
pywikibot.output(u"** Already done.")
else:
text = pywikibot.replaceCategoryLinks(
text + u"{{commons|%s}}" % commonspage.title(), page.categories()
)
if oldText != text:
pywikibot.showDiff(oldText, text)
if not self.acceptall:
choice = pywikibot.inputChoice(
u"Do you want to accept these changes?",
["Yes", "No", "All"],
["y", "N", "a"],
"N",
)
if choice == "a":
self.acceptall = True
if self.acceptall or choice == "y":
try:
msg = pywikibot.translate(pywikibot.getSite(), comment1)
page.put(text, msg)
except pywikibot.EditConflict:
pywikibot.output(u"Skipping %s because of edit " u"conflict" % (page.title()))
except pywikibot.NoPage:
pywikibot.output(u"Page does not exist in Commons!")
except pywikibot.NoPage:
pywikibot.output(u"Page %s does not exist?!" % page.title())
except pywikibot.IsRedirectPage:
pywikibot.output(u"Page %s is a redirect; skipping." % page.title())
except pywikibot.LockedPage:
pywikibot.output(u"Page %s is locked?!" % page.title())
示例9: replaceCategories
def replaceCategories(page, oldcats, newcat):
oldtext = page.get()
newcats = []
newcats.append(newcat)
for cat in page.categories():
if not (cat.titleWithoutNamespace()==oldcats[0].titleWithoutNamespace() or cat.titleWithoutNamespace()==oldcats[1].titleWithoutNamespace()):
newcats.append(cat)
newtext = wikipedia.replaceCategoryLinks (oldtext, newcats)
comment = u'[[' + oldcats[0].title() + u']] \u2229 [[' + oldcats[1].title() + u']] (and 3 levels of subcategories) -> [[' + newcat.title() + u']]'
wikipedia.showDiff(oldtext, newtext)
page.put(newtext, comment)
示例10: add_category
def add_category(article, category, comment=None, createEmptyPages=False):
"""Given an article and a category, adds the article to the category."""
cats = article.categories(get_redirect=True)
if not category in cats:
cats.append(category)
try:
text = article.get()
except pywikibot.NoPage:
if createEmptyPages:
text = ""
else:
raise
text = pywikibot.replaceCategoryLinks(text, cats)
try:
article.put(text, comment=comment)
except pywikibot.EditConflict:
pywikibot.output(u"Skipping %s because of edit conflict" % article.title())
示例11: pages
def pages(self):
for page in self.generator:
try:
wikipedia.output(u'\n>>>> %s <<<<' % page.title())
commons = wikipedia.getSite('commons', 'commons')
commonspage = wikipedia.Page(commons, page.title())
try:
getcommons = commonspage.get(get_redirect=True)
if page.title() == commonspage.title():
oldText = page.get()
text = oldText
# for commons template
findTemplate=re.compile(ur'\{\{[Cc]ommonscat')
s = findTemplate.search(text)
findTemplate2=re.compile(ur'\{\{[Ss]isterlinks')
s2 = findTemplate2.search(text)
if s or s2:
wikipedia.output(u'** Already done.')
else:
text = wikipedia.replaceCategoryLinks(text+u'{{commons|%s}}'%commonspage.title(), page.categories())
if oldText != text:
wikipedia.showDiff(oldText, text)
if not self.acceptall:
choice = wikipedia.inputChoice(u'Do you want to accept these changes?', ['Yes', 'No', 'All'], ['y', 'N', 'a'], 'N')
if choice == 'a':
self.acceptall = True
if self.acceptall or choice == 'y':
try:
msg = wikipedia.translate(wikipedia.getSite(), comment1)
page.put(text, msg)
except wikipedia.EditConflict:
wikipedia.output(u'Skipping %s because of edit conflict' % (page.title()))
except wikipedia.NoPage:
wikipedia.output(u'Page does not exist in Commons!')
except wikipedia.NoPage:
wikipedia.output(u'Page %s does not exist?!' % page.title())
except wikipedia.IsRedirectPage:
wikipedia.output(u'Page %s is a redirect; skipping.' % page.title())
except wikipedia.LockedPage:
wikipedia.output(u'Page %s is locked?!' % page.title())
示例12: categorizeImage
def categorizeImage(page, conn, cursor):
wikipedia.output(u'Working on: %s' % page.title())
templates = page.templates()
if not u'Rijksmonument' in page.templates():
wikipedia.output(u'Rijksmonument template not found at: %s' % page.title())
return False
rijksmonumentid=-1
for (template, params) in page.templatesWithParams():
if template==u'Rijksmonument':
if len(params)==1:
try:
rijksmonumentid = int(params[0])
except ValueError:
wikipedia.output(u'Unable to extract a valid id')
break
if (rijksmonumentid < 0 or 600000 < rijksmonumentid ):
wikipedia.output(u'Invalid id')
return False
rijksmonumentenLijst = getList(rijksmonumentid, conn, cursor)
if not rijksmonumentenLijst:
return False
oldtext = page.get()
currentcats = page.categories()
newcats = getCategories(rijksmonumentenLijst)
if newcats:
for currentcat in currentcats:
if not currentcat.title()==u'Category:Rijksmonumenten':
newcats.append(currentcat)
# Remove dupes
newcats = list(set(newcats))
newtext = wikipedia.replaceCategoryLinks(oldtext, newcats)
comment = u'Adding categories based on Rijksmonument identifier'
wikipedia.showDiff(oldtext, newtext)
page.put(newtext, comment)
示例13: include
def include(pl,checklinks=True,realinclude=True,linkterm=None):
cl = checklinks
if linkterm:
actualworkingcat = catlib.Category(mysite,workingcat.title(),
sortKey=linkterm)
else:
actualworkingcat = workingcat
if realinclude:
try:
text = pl.get()
except pywikibot.NoPage:
pass
except pywikibot.IsRedirectPage:
cl = True
pass
else:
cats = pl.categories()
if not workingcat in cats:
cats = pl.categories()
for c in cats:
if c in parentcats:
if removeparent:
catlib.change_category(pl,c,actualworkingcat)
break
else:
pl.put(pywikibot.replaceCategoryLinks(
text, cats + [actualworkingcat]))
if cl:
if checkforward:
for page2 in pl.linkedPages():
if needcheck(page2):
tocheck.append(page2)
checked[page2] = page2
if checkbackward:
for refPage in pl.getReferences():
if needcheck(refPage):
tocheck.append(refPage)
checked[refPage] = refPage
示例14: main
def main(args):
'''
Main loop.
'''
site = wikipedia.getSite(u'commons', u'commons')
wikipedia.setSite(site)
conn = None
cursor = None
(conn, cursor) = connectDatabase()
conn2 = None
cursor2 = None
(conn2, cursor2) = connectDatabase2('commonswiki-p.db.toolserver.org', u'commonswiki_p')
imageSet = getImagesToCorrect(cursor2)
#print imageSet
for (pageName, fileId) in imageSet:
wikipedia.output(pageName)
if not pageName==u'' and not fileId==u'':
#Get page contents
page = wikipedia.Page(site, pageName)
if page.exists():
categories = page.categories()
#Get metadata
metadata = getMetadata(fileId, cursor)
#Check if we got metadata
if metadata:
#Get description
description = getDescription(metadata)
description = wikipedia.replaceCategoryLinks(description, categories, site)
comment= u'Fixing description of Geograph image with broken template'
wikipedia.output(description)
page.put(description, comment)
示例15: add_category
def add_category(sort_by_last_name=False, create_pages=False):
"""A robot to mass-add a category to a list of pages."""
site = pywikibot.getSite()
if gen:
newcatTitle = pywikibot.input(u"Category to add (do not give namespace):")
if not site.nocapitalize:
newcatTitle = newcatTitle[:1].capitalize() + newcatTitle[1:]
# set edit summary message
editSummary = pywikibot.translate(site, msg_add) % newcatTitle
cat_namespace = site.category_namespaces()[0]
answer = ""
for page in gen:
if answer != "a":
answer = ""
while answer not in ("y", "n", "a"):
answer = pywikibot.inputChoice(u"%s" % (page.aslink()), ["Yes", "No", "All"], ["y", "n", "a"], "n")
if answer == "a":
confirm = pywikibot.inputChoice(
u"""\
This should be used if and only if you are sure that your links are correct!
Are you sure?""",
["Yes", "No"],
["y", "n"],
"n",
)
if confirm == "n":
answer = ""
if answer == "y" or answer == "a":
try:
text = page.get()
except pywikibot.NoPage:
if create_pages:
pywikibot.output(u"%s doesn't exist yet. Creating." % (page.title()))
text = ""
else:
pywikibot.output(u"%s doesn't exist yet. Ignoring." % (page.title()))
continue
except pywikibot.IsRedirectPage, arg:
redirTarget = pywikibot.Page(site, arg.args[0])
pywikibot.output(u"WARNING: %s is redirect to %s. Ignoring." % (page.title(), redirTarget.title()))
continue
cats = page.categories()
# Show the title of the page we're working on.
# Highlight the title in purple.
pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<" % page.title())
pywikibot.output(u"Current categories:")
for cat in cats:
pywikibot.output(u"* %s" % cat.title())
catpl = pywikibot.Page(site, cat_namespace + ":" + newcatTitle)
if sort_by_last_name:
catpl = sorted_by_last_name(catpl, page)
if catpl in cats:
pywikibot.output(u"%s is already in %s." % (page.title(), catpl.title()))
else:
pywikibot.output(u"Adding %s" % catpl.aslink())
cats.append(catpl)
text = pywikibot.replaceCategoryLinks(text, cats)
try:
page.put(text, comment=editSummary)
except pywikibot.EditConflict:
pywikibot.output(u"Skipping %s because of edit conflict" % (page.title()))