• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python wikipedia.replaceCategoryLinks函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中wikipedia.replaceCategoryLinks函数的典型用法代码示例。如果您正苦于以下问题:Python replaceCategoryLinks函数的具体用法?Python replaceCategoryLinks怎么用?Python replaceCategoryLinks使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了replaceCategoryLinks函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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))
开发者ID:MrTweek,项目名称:lanigiro,代码行数:26,代码来源:category.py


示例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))
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:8,代码来源:catall.py


示例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'))
开发者ID:edgarskos,项目名称:pywikipedia-git,代码行数:9,代码来源:catall.py


示例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())
开发者ID:Rodehi,项目名称:GFROS,代码行数:56,代码来源:commons_link.py


示例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
开发者ID:bymerej,项目名称:ts-multichill-bot,代码行数:56,代码来源:add_rijksmonument_template.py


示例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
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:10,代码来源:cosmetic_changes.py


示例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())
开发者ID:yknip1207,项目名称:genewiki,代码行数:52,代码来源:commons_link.py


示例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())
开发者ID:hroest,项目名称:pywikibot-compat,代码行数:50,代码来源:commons_link.py


示例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)
开发者ID:bymerej,项目名称:ts-multichill-bot,代码行数:14,代码来源:intersect_categories.py


示例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())
开发者ID:hasteur,项目名称:UAABOT,代码行数:18,代码来源:catlib.py


示例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())
开发者ID:VisualEffects,项目名称:pywikia,代码行数:43,代码来源:commons_link.py


示例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)
开发者ID:bymerej,项目名称:ts-multichill-bot,代码行数:41,代码来源:categorize_rijksmonumenten.py


示例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
开发者ID:NaturalSolutions,项目名称:ecoReleve-Concepts,代码行数:38,代码来源:makecat.py


示例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)
开发者ID:multichill,项目名称:toollabs,代码行数:37,代码来源:description_restoration.py


示例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()))
开发者ID:dantman,项目名称:pywikia,代码行数:66,代码来源:category.py


示例16: add_text


#.........这里部分代码省略.........
        result = re.findall(regexSkip, text)
        if result != []:
            pywikibot.output(
u'''Exception! regex (or word) used with -except is in the page. Skipping!
Match was: %s''' % result)
            return (False, False, always) # continue
    # If not up, text put below
    if not up:
        newtext = text
        # Translating the \\n into binary \n
        addText = addText.replace('\\n', '\n')
        if (reorderEnabled):
            # Getting the categories
            categoriesInside = pywikibot.getCategoryLinks(newtext, site)
            # Deleting the categories
            newtext = pywikibot.removeCategoryLinks(newtext, site)
            # Getting the interwiki
            interwikiInside = pywikibot.getLanguageLinks(newtext, site)
            # Removing the interwiki
            newtext = pywikibot.removeLanguageLinks(newtext, site)
            # nn got a message between the categories and the iw's
            # and they want to keep it there, first remove it
            hasCommentLine = False
            if (site.language()==u'nn'):
                regex = re.compile('(<!-- ?interwiki \(no(?:/nb)?, ?sv, ?da first; then other languages alphabetically by name\) ?-->)')
                found = regex.findall(newtext)
                if found:
                    hasCommentLine = True
                    newtext = regex.sub('', newtext)

            # Adding the text
            newtext += u"\n%s" % addText
            # Reputting the categories
            newtext = pywikibot.replaceCategoryLinks(newtext,
                                                 categoriesInside, site, True)
            #Put the nn iw message back
            if site.language()==u'nn' and (interwikiInside or hasCommentLine):
                newtext = newtext + u'\r\n\r\n' + nn_iw_msg
            # Dealing the stars' issue
            allstars = []
            starstext = pywikibot.removeDisabledParts(text)
            for star in starsList:
                regex = re.compile('(\{\{(?:template:|)%s\|.*?\}\}[\s]*)' % star,
                                   re.I)
                found = regex.findall(starstext)
                if found != []:
                    newtext = regex.sub('', newtext)
                    allstars += found
            if allstars != []:
                newtext = newtext.strip()+'\r\n\r\n'
                allstars.sort()
                for element in allstars:
                    newtext += '%s\r\n' % element.strip()
            # Adding the interwiki
            newtext = pywikibot.replaceLanguageLinks(newtext, interwikiInside, site)
        else:
            # Adding the text
            newtext += u"\n%s" % addText
    # If instead the text must be added above...
    else:
        newtext = addText + '\n' + text
    if putText and text != newtext:
        pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                         % page.title())
        pywikibot.showDiff(text, newtext)
    # Let's put the changes.
开发者ID:RileyHuntley,项目名称:Italic-title-bot,代码行数:67,代码来源:Italic+title.py


示例17: standardizePageFooter

    def standardizePageFooter(self, text):
        """
        Makes sure that interwiki links, categories and star templates are
        put to the correct position and into the right order. This combines the
        old instances standardizeInterwiki and standardizeCategories
        The page footer has the following section in that sequence:
        1. categories
        2. additional information depending on local site policy
        3. stars templates for featured and good articles
        4. interwiki links
        """
        starsList = [
            u'bueno',
            u'bom interwiki',
            u'cyswllt[ _]erthygl[ _]ddethol', u'dolen[ _]ed',
            u'destacado', u'destaca[tu]',
            u'enllaç[ _]ad',
            u'enllaz[ _]ad',
            u'leam[ _]vdc',
            u'legătură[ _]a[bcf]',
            u'liamm[ _]pub',
            u'lien[ _]adq',
            u'lien[ _]ba',
            u'liên[ _]kết[ _]bài[ _]chất[ _]lượng[ _]tốt',
            u'liên[ _]kết[ _]chọn[ _]lọc',
            u'ligam[ _]adq',
            u'ligoelstara',
            u'ligoleginda',
            u'link[ _][afgu]a', u'link[ _]adq', u'link[ _]f[lm]', u'link[ _]km',
            u'link[ _]sm', u'linkfa',
            u'na[ _]lotura',
            u'nasc[ _]ar',
            u'tengill[ _][úg]g',
            u'ua',
            u'yüm yg',
            u'רא',
            u'وصلة مقالة جيدة',
            u'وصلة مقالة مختارة',
        ]

        categories = None
        interwikiLinks = None
        allstars = []
        hasCommentLine = False

        # The PyWikipediaBot is no longer allowed to touch categories on the
        # German Wikipedia. See
        # http://de.wikipedia.org/wiki/Hilfe_Diskussion:Personendaten/Archiv/1#Position_der_Personendaten_am_.22Artikelende.22
        # ignoring nn-wiki of cause of the comment line above iw section
        if not self.template and not '{{Personendaten' in text:
            categories = pywikibot.getCategoryLinks(text, site = self.site)

        if not self.talkpage:# and pywikibot.calledModuleName() <> 'interwiki':
            subpage = False
            if self.template:
                loc = None
                try:
                    tmpl, loc = moved_links[self.site.lang]
                    del tmpl
                except KeyError:
                    pass
                if loc != None and loc in self.title:
                    subpage = True
            interwikiLinks = pywikibot.getLanguageLinks(
                text, insite=self.site, template_subpage=subpage)

            # Removing the interwiki
            text = pywikibot.removeLanguageLinks(text, site = self.site)
            # Removing the stars' issue
            starstext = pywikibot.removeDisabledParts(text)
            for star in starsList:
                regex = re.compile('(\{\{(?:template:|)%s\|.*?\}\}[\s]*)'
                                   % star, re.I)
                found = regex.findall(starstext)
                if found != []:
                    if pywikibot.verbose:
                        print found
                    text = regex.sub('', text)
                    allstars += found

        # nn got a message between the categories and the iw's
        # and they want to keep it there, first remove it
        if self.site.lang in msg_interwiki:
            iw_msg = msg_interwiki[self.site.lang]
            if isinstance(iw_msg, tuple):
                iw_reg = iw_msg[1]
                iw_msg = iw_msg[0]
            else:
                iw_reg = u'(%s)' % iw_msg
            regex = re.compile(iw_reg)
            found = regex.findall(text)
            if found:
                if pywikibot.verbose:
                    print found
                hasCommentLine = True
                text = regex.sub('', text)

        # Adding categories
        if categories:
            text = pywikibot.replaceCategoryLinks(text, categories,
#.........这里部分代码省略.........
开发者ID:Protonk,项目名称:pywikipedia2,代码行数:101,代码来源:cosmetic_changes.py


示例18: featuredWithInterwiki

def featuredWithInterwiki(fromsite, tosite, template_on_top):
    if not fromsite.lang in cache:
        cache[fromsite.lang]={}
    if not tosite.lang in cache[fromsite.lang]:
        cache[fromsite.lang][tosite.lang]={}
    cc=cache[fromsite.lang][tosite.lang]
    if nocache:
        cc={}

    try:
        templatelist = template[tosite.lang]
        templatelist += template['_default']
    except KeyError:
        templatelist = template['_default']

    findtemplate = '(' + '|'.join(templatelist) + ')'
    re_Link_FA=re.compile(ur"\{\{%s\|%s\}\}" % (findtemplate.replace(u' ', u'[ _]'), fromsite.lang), re.IGNORECASE)
    re_this_iw=re.compile(ur"\[\[%s:[^]]+\]\]" % fromsite.lang)

    arts=featuredArticles(fromsite)

    pairs=[]
    for a in arts:
        if a.title()<afterpage:
            continue
        if u"/" in a.title() and a.namespace() != 0:
            wikipedia.output(u"%s is a subpage" % a.title())
            continue
        if a.title() in cc:
            wikipedia.output(u"(cached) %s -> %s"%(a.title(), cc[a.title()]))
            continue
        if a.isRedirectPage():
            a=a.getRedirectTarget()
        try:
            if not a.exists():
                wikipedia.output(u"source page doesn't exist: %s" % a.title())
                continue
            atrans=findTranslated(a,tosite)
            if atrans:
                text=atrans.get()
                m=re_Link_FA.search(text)
                if m:
                    wikipedia.output(u"(already done)")
                else:
                    # insert just before interwiki
                    if (not interactive or
                        wikipedia.input(u'Connecting %s -> %s. Proceed? [Y/N]'%(a.title(), atrans.title())) in ['Y','y']
                        ):
                        m=re_this_iw.search(text)
                        if not m:
                            wikipedia.output(u"no interwiki record, very strange")
                            continue
                        comment = wikipedia.setAction(wikipedia.translate(wikipedia.getSite(), msg) % (fromsite.lang, a.title()))

                        ### Moving {{Link FA|xx}} to top of interwikis ###
                        if template_on_top == True:
                            text=wikipedia.replaceCategoryLinks(text+(u"{{%s|%s}}"%(templatelist[0], fromsite.lang)), atrans.categories())

                        ### Placing {{Link FA|xx}} right next to corresponding interwiki ###
                        else:
                            text=(text[:m.end()]
                                  + (u" {{%s|%s}}" % (templatelist[0], fromsite.lang))
                                  + text[m.end():])

                        try:
                            atrans.put(text, comment)
                        except wikipedia.LockedPage:
                            wikipedia.output(u'Page %s is locked!' % atrans.title())

                cc[a.title()]=atrans.title()
        except wikipedia.PageNotSaved, e:
            wikipedia.output(u"Page not saved")
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:72,代码来源:featured.py


示例19: add_text

def add_text(page=None, addText=None, summary=None, regexSkip=None,
             regexSkipUrl=None, always=False, up=False, putText=True,
             oldTextGiven=None, reorderEnabled=True, create=False):
    # When a page is tagged as "really well written" it has a star in the
    # interwiki links. This is a list of all the templates used (in regex
    # format) to make the stars appear.
    starsList = [
        u'bueno',
        u'bom interwiki',
        u'cyswllt[ _]erthygl[ _]ddethol', u'dolen[ _]ed',
        u'destacado', u'destaca[tu]',
        u'enllaç[ _]ad',
        u'enllaz[ _]ad',
        u'leam[ _]vdc',
        u'legătură[ _]a[bcf]',
        u'liamm[ _]pub',
        u'lien[ _]adq',
        u'lien[ _]ba',
        u'liên[ _]kết[ _]bài[ _]chất[ _]lượng[ _]tốt',
        u'liên[ _]kết[ _]chọn[ _]lọc',
        u'ligam[ _]adq',
        u'ligoelstara',
        u'ligoleginda',
        u'link[ _][afgu]a', u'link[ _]adq', u'link[ _]f[lm]', u'link[ _]km',
        u'link[ _]sm', u'linkfa',
        u'na[ _]lotura',
        u'nasc[ _]ar',
        u'tengill[ _][úg]g',
        u'ua',
        u'yüm yg',
        u'רא',
        u'وصلة مقالة جيدة',
        u'وصلة مقالة مختارة',
    ]

    errorCount = 0
    site = pywikibot.getSite()
    pathWiki = site.family.nicepath(site.lang)
    site = pywikibot.getSite()
    if oldTextGiven is None:
        try:
            text = page.get()
        except pywikibot.NoPage:
            if create:
                pywikibot.output(u"%s doesn't exist, creating it!"
                                 % page.title())
                text = u''
            else:
                pywikibot.output(u"%s doesn't exist, skip!" % page.title())
                return (False, False, always)
        except pywikibot.IsRedirectPage:
            pywikibot.output(u"%s is a redirect, skip!" % page.title())
            return (False, False, always)
    else:
        text = oldTextGiven
    # If not up, text put below
    if not up:
        newtext = text
        # Translating the \\n into binary \n
        addText = addText.replace('\\n', '\n')
        if (reorderEnabled):
            # Getting the categories
            categoriesInside = pywikibot.getCategoryLinks(newtext, site)
            # Deleting the categories
            newtext = pywikibot.removeCategoryLinks(newtext, site)
            # Getting the interwiki
            interwikiInside = pywikibot.getLanguageLinks(newtext, site)
            # Removing the interwiki
            newtext = pywikibot.removeLanguageLinks(newtext, site)

            # Adding the text
            newtext += u"\n%s" % addText
            # Reputting the categories
            newtext = pywikibot.replaceCategoryLinks(newtext,
                                                     categoriesInside, site,
                                                     True)
            # Dealing the stars' issue
            allstars = []
            starstext = pywikibot.removeDisabledParts(text)
            for star in starsList:
                regex = re.compile('(\{\{(?:template:|)%s\|.*?\}\}[\s]*)'
                                   % star, re. 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python wikipedia.replaceExcept函数代码示例发布时间:2022-05-26
下一篇:
Python wikipedia.removeDisabledParts函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap