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

Python wikipedia.replaceLanguageLinks函数代码示例

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

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



在下文中一共展示了replaceLanguageLinks函数的19个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: processMeaning

    def processMeaning(self, compId, namespace, activeLangs, meaning):
        """Updates all the pages in a given cluster."""
        if self.opts.verbose:
            niceText = '[' + ', '.join(map(lambda p: p[0] + ':' + p[1], meaning)) + ']'
            print 'DEBUG: Processing meaning: %s' % (niceText,)

        # Load pages
        pages = {}
        for page in meaning:
            lang, title = page
            if not lang in activeLangs:
                continue
            site = wikipedia.getSite(lang)
            page = wikipedia.Page(site, title, site, namespace)
            if self.opts.verbose:
                print 'DEBUG: Fetching page: %s' % (page,)
            if not page.exists():
                print 'WARNING: Skipping this meaning because of nonexistent page: %s' % (page,)
                return
            if page.isRedirectPage():
                print 'WARNING: Skipping this meaning because of unexpected redirect page: %s' % (page,)
                return
            pages[site] = page

        # Process each page
        for page in pages.values():
            interwiki = {}
            for p in page.interwiki():
                interwiki[p.site()] = p

            # Find interwikis to add/change/remove
            add, change, remove = [], [], []
            for site in interwiki:
                if not site in pages:
                    remove += [str(site.language())]
                    continue
                if interwiki[site] != pages[site]:
                    change += [str(site.language())]
                    continue
            
            otherPages = {}
            for site in pages:
                if page.site() == site:
                    continue
                otherPages[site] = page
            
            for site in otherPages:
                if not site in interwiki:
                    add += [str(site.language())]

            # Check if update needed
            if not add and not change and not remove:
                continue
            
            # Update the page
            comment = self.reportMods(add, change, remove)
            print 'INFO: page: %s %s' % (page, comment)
            if not self.opts.dry:
                text = wikipedia.replaceLanguageLinks(page.get(), otherPages)
                page.put(text, comment)
开发者ID:bolo1729,项目名称:interwiki-analysis-old,代码行数:60,代码来源:interwiki_analysis_commit.py


示例2: updateInterwiki

    def updateInterwiki (self, wikipediaPage = None, commonsPage = None):
        '''
        Update the interwiki's at commons from a wikipedia page. The bot just
        replaces the interwiki links at the commons page with the interwiki's from
        the wikipedia page. This should probably be more intelligent. We could use
        add all the interwiki's and remove duplicates. Or only remove language links
        if multiple language links to the same language exist.

        This function is disabled for the moment untill i figure out what the best
        way is to update the interwiki's.
        '''
        interwikis = {}
        comment= u''
        interwikilist = wikipediaPage.interwiki()
        interwikilist.append(wikipediaPage)

        for interwikiPage in interwikilist:
            interwikis[interwikiPage.site()]=interwikiPage
        oldtext = commonsPage.get()
        # The commonssite object doesnt work with interwiki's
        newtext = pywikibot.replaceLanguageLinks(oldtext, interwikis,
                                                 pywikibot.getSite(u'nl'))
        comment = u'Updating interwiki\'s from [[' + \
                  wikipediaPage.site().language()  + \
                  u':' + wikipediaPage.title() + u']]'

        if newtext != oldtext:
            #This doesnt seem to work. Newtext has some trailing whitespace
            pywikibot.showDiff(oldtext, newtext)
            commonsPage.put(newtext=newtext, comment=comment)
开发者ID:electionr,项目名称:rootstriker-fec-bot,代码行数:30,代码来源:commonscat.py


示例3: standardizeInterwiki

 def standardizeInterwiki(self, text):
     """
     Makes sure that interwiki links are put to the correct position and
     into the right order.
     """
     interwikiLinks = wikipedia.getLanguageLinks(text, insite = self.site)
     text = wikipedia.replaceLanguageLinks(text, interwikiLinks, site = self.site)
     return text
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:8,代码来源:cosmetic_changes.py


示例4: 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


示例5: run

 def run(self):
     hints, removeHints = self.warnfileReader.getHints()
     k=hints.keys()
     k.sort()
     print "Fixing... %i pages" % len(k)
     for page in k:
         old={}
         try:
             for page2 in page.interwiki():
                 old[page2.site()] = page2
         except pywikibot.IsRedirectPage:
             pywikibot.output(u"%s is a redirect page; not changing"
                              % page.title(asLink=True))
             continue
         except pywikibot.NoPage:
             pywikibot.output(u"Page %s not found; skipping"
                              % page.title(asLink=True))
             continue
         new={}
         new.update(old)
         if page in hints:
             for page2 in hints[page]:
                 site = page2.site()
                 new[site] = page2
         if page in removeHints:
             for page2 in removeHints[page]:
                 site = page2.site()
                 try:
                     del new[site]
                 except KeyError:
                     pass
         mods, adding, removing, modifying = interwiki.compareLanguages(old,
                                                                        new,
                                                                        insite=page.site())
         if mods:
             pywikibot.output(page.title(asLink=True) + mods)
             oldtext = page.get()
             newtext = pywikibot.replaceLanguageLinks(oldtext, new)
             if 1:
                 pywikibot.showDiff(oldtext, newtext)
                 try:
                     status, reason, data = page.put(newtext,
                                                     comment='warnfile '+mods)
                 except pywikibot.LockedPage:
                     pywikibot.output(u"Page is locked. Skipping.")
                     continue
                 except pywikibot.SpamfilterError, e:
                     pywikibot.output(
                         u'Cannot change %s because of blacklist entry %s'
                         % (page.title(), e.url))
                     continue
                 except pywikibot.Error:
                     pywikibot.output(u"Error while saving page.")
                     continue
                 if str(status) != '302':
                     print status, reason
开发者ID:edgarskos,项目名称:pywikipedia-git,代码行数:56,代码来源:warnfile.py


示例6: add_text


#.........这里部分代码省略.........
    # In this way you can use both -except and -excepturl
    if regexSkipUrl != None:
        url = "%s%s" % (pathWiki, page.urlname())
        result = re.findall(regexSkipUrl, site.getUrl(url))
        if result != []:
            wikipedia.output(u"Exception! regex (or word) used with -exceptUrl is in the page. Skip!")
            return (False, False, always)  # continue
    if regexSkip != None:
        result = re.findall(regexSkip, text)
        if result != []:
            wikipedia.output(u"Exception! regex (or word) used with -except is in the page. Skip!")
            return (False, False, always)  # continue
    # If not up, text put below
    if not up:
        newtext = text
        # Getting the categories
        categoriesInside = wikipedia.getCategoryLinks(newtext, site)
        # Deleting the categories
        newtext = wikipedia.removeCategoryLinks(newtext, site)
        # Getting the interwiki
        interwikiInside = wikipedia.getLanguageLinks(newtext, site)
        # Removing the interwiki
        newtext = wikipedia.removeLanguageLinks(newtext, site)
        # nn got a message between the categories and the iw's and they want to keep it there, first remove it
        if site.language() == u"nn":
            newtext = newtext.replace(nn_iw_msg, "")
        # Translating the \\n into binary \n
        addText = addText.replace("\\n", "\n")
        # Adding the text
        newtext += u"\n%s" % addText
        # Reputting the categories
        newtext = wikipedia.replaceCategoryLinks(newtext, categoriesInside, site, True)
        # Put the nn iw message back
        if site.language() == u"nn":
            newtext = newtext + u"\n" + nn_iw_msg
        # Dealing the stars' issue
        allstars = []
        starstext = wikipedia.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 = wikipedia.replaceLanguageLinks(newtext, interwikiInside, site)
    # If instead the text must be added above...
    else:
        newtext = addText + "\n" + text
    if putText and text != newtext:
        wikipedia.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<" % page.title())
        wikipedia.showDiff(text, newtext)
    # Let's put the changes.
    while True:
        # If someone load it as module, maybe it's not so useful to put the
        # text in the page
        if putText:
            if not always:
                choice = wikipedia.inputChoice(
                    u"Do you want to accept these changes?", ["Yes", "No", "All"], ["y", "N", "a"], "N"
                )
                if choice == "a":
                    always = True
                elif choice == "n":
                    return (False, False, always)
            if always or choice == "y":
                try:
                    if always:
                        page.put(newtext, summary)
                    else:
                        page.put_async(newtext, summary)
                except wikipedia.EditConflict:
                    wikipedia.output(u"Edit conflict! skip!")
                    return (False, False, always)
                except wikipedia.ServerError:
                    errorCount += 1
                    if errorCount < 5:
                        wikipedia.output(u"Server Error! Wait..")
                        time.sleep(5)
                        continue
                    else:
                        raise wikipedia.ServerError(u"Fifth Server Error!")
                except wikipedia.SpamfilterError, e:
                    wikipedia.output(u"Cannot change %s because of blacklist entry %s" % (page.title(), e.url))
                    return (False, False, always)
                except wikipedia.PageNotSaved, error:
                    wikipedia.output(u"Error putting page: %s" % error.args)
                    return (False, False, always)
                except wikipedia.LockedPage:
                    wikipedia.output(u"Skipping %s (locked page)" % page.title())
                    return (False, False, always)
                else:
                    # Break only if the errors are one after the other...
                    errorCount = 0
                    return (True, True, always)
开发者ID:dantman,项目名称:pywikia,代码行数:101,代码来源:add_text.py


示例7: standardizePageFooter


#.........这里部分代码省略.........
            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'ligazón[ _]a[bd]',
            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 = []

        # 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 '{{Personendaten' not in text and \
           '{{SORTIERUNG' not in text and '{{DEFAULTSORT' not in text and \
           self.site.lang not in ('et', 'it', 'bg', 'ru'):
            try:
                categories = pywikibot.getCategoryLinks(text, site=self.site)
            # there are categories like [[categoy:Foo {{#time:Y...}}]]
            except pywikibot.InvalidTitle:
                pass

        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 is not 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 != []:
                    text = regex.sub('', text)
                    allstars += found

        # Adding categories
        if categories:
            ##Sorting categories in alphabetic order. beta test only on Persian Wikipedia, TODO fix bug for sorting
            #if self.site.language() == 'fa':
            #   categories.sort()
            ##Taking main cats to top
            #   for name in categories:
            #       if re.search(u"(.+?)\|(.{,1}?)",name.title()) or name.title()==name.title().split(":")[0]+title:
            #            categories.remove(name)
            #            categories.insert(0, name)
            text = pywikibot.replaceCategoryLinks(text, categories,
                                                  site=self.site)
        # Adding stars templates
        if allstars:
            text = text.strip() + self.site.family.interwiki_text_separator
            allstars.sort()
            for element in allstars:
                text += '%s\r\n' % element.strip()
                if pywikibot.verbose:
                    pywikibot.output(u'%s' % element.strip())

        # Adding the interwiki
        if interwikiLinks:
            text = pywikibot.replaceLanguageLinks(text, interwikiLinks,
                                                  site=self.site,
                                                  template=self.template,
                                                  template_subpage=subpage)
        return text
开发者ID:Rodehi,项目名称:GFROS,代码行数:101,代码来源:cosmetic_changes.py


示例8: standardizePageFooter


#.........这里部分代码省略.........
            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/bis_2006#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.language() == "nn":
            regex = re.compile(
                "(<!-- ?interwiki \(no(?:/nb)?, ?sv, ?da first; then other languages alphabetically by name\) ?-->)"
            )
            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, site=self.site)
        # Put the nn iw message back
        if self.site.language() == "nn" and not self.talkpage and (interwikiLinks or hasCommentLine):
            text = text + "\r\n\r\n" + nn_iw_msg
        # Adding stars templates
        if allstars:
            text = text.strip() + self.site.family.interwiki_text_separator
            allstars.sort()
            for element in allstars:
                text += "%s\r\n" % element.strip()
                if pywikibot.verbose:
                    pywikibot.output(u"%s" % element.strip())
        # Adding the interwiki
        if interwikiLinks:
            text = pywikibot.replaceLanguageLinks(
                text, interwikiLinks, site=self.site, template=self.template, template_subpage=subpage
            )
        return text
开发者ID:swertschak,项目名称:wikijournals-api,代码行数:101,代码来源:cosmetic_changes.py


示例9: str

# What follows is the main part of the code.
try:
    for pl in site.allpages(start):
        plname = pl.title()
        pywikibot.output(u'\nLoading %s...' % plname)
        try:
            oldtext = pl.get()
        except pywikibot.IsRedirectPage:
            pywikibot.output(u"%s is a redirect!" % plname)
            continue
        old = pl.interwiki()
        new = {}
        for pl2 in old:
            new[pl2.site()] = pl2
        newtext = pywikibot.replaceLanguageLinks(oldtext, new)
        if new:
            if oldtext != newtext:
                pywikibot.showDiff(oldtext, newtext)
                # Submit changes
                try:
                    status, reason, data = pl.put(newtext, comment=comm)
                    if str(status) != '302':
                        pywikibot.output(status, reason)
                except pywikibot.LockedPage:
                    pywikibot.output(u"%s is locked" % plname)
                    continue
            else:
                pywikibot.output(u'No changes needed.')
                continue
        else:
开发者ID:Botomatik,项目名称:JackBot,代码行数:30,代码来源:standardize_interwiki.py


示例10: featuredWithInterwiki

def featuredWithInterwiki(fromsite, tosite, template_on_top, pType, quiet, dry = False):
    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={}

    templatelist = getTemplateList(tosite.lang, pType)
    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, pType)

    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, quiet)
            if pType!='former':
                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
                            site = wikipedia.getSite()
                            if pType == 'good':
                                comment = wikipedia.setAction(wikipedia.translate(site, msg_good) % (fromsite.lang, a.title()))
                            elif pType == 'list':
                                comment = wikipedia.setAction(wikipedia.translate(site, msg_lists) % (fromsite.lang, a.title()))
                            else:
                                comment = wikipedia.setAction(wikipedia.translate(site, msg) % (fromsite.lang, a.title()))
                            ### Moving {{Link FA|xx}} to top of interwikis ###
                            if template_on_top == True:
                                # Getting the interwiki
                                iw = wikipedia.getLanguageLinks(text, site)
                                # Removing the interwiki
                                text = wikipedia.removeLanguageLinks(text, site)
                                text += u"\r\n{{%s|%s}}\r\n"%(templatelist[0], fromsite.lang)
                                # Adding the interwiki
                                text = wikipedia.replaceLanguageLinks(text, iw, site)

                            ### Placing {{Link FA|xx}} right next to corresponding interwiki ###
                            else:
                                text=(text[:m.end()]
                                      + (u" {{%s|%s}}" % (templatelist[0], fromsite.lang))
                                      + text[m.end():])
                            if not dry:
                                try:
                                    atrans.put(text, comment)
                                except wikipedia.LockedPage:
                                    wikipedia.output(u'Page %s is locked!' % atrans.title())
                    cc[a.title()]=atrans.title()
            else:
                if atrans:
                    text=atrans.get()
                    m=re_Link_FA.search(text)
                    if m:
                        # 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
                            site = wikipedia.getSite()
                            comment = wikipedia.setAction(wikipedia.translate(site, msg_former) % (fromsite.lang, a.title()))
                            name=templatelist[0]
                            name2=name[0].lower()+name[1:]
                            text=text.replace(u"{{%s|%s}}" %(name, fromsite.lang),'',1)
                            text=text.replace(u"{{%s|%s}}" %(name2, fromsite.lang),'',1)
                            if not dry:
                                try:
                                    atrans.put(text, comment)
                                except wikipedia.LockedPage:
                                    wikipedia.output(u'Page %s is locked!' % atrans.title())
#.........这里部分代码省略.........
开发者ID:yknip1207,项目名称:genewiki,代码行数:101,代码来源:featured.py


示例11: featuredbot

def featuredbot(arts, cc, tosite, template_on_top, pType, quiet, dry):
    templatelist = getTemplateList(tosite.lang, pType)
    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)
    pairs=[]
    for a in arts:
        if a.title() < afterpage:
            continue
        if u"/" in a.title() and a.namespace() != 0:
            pywikibot.output(u"%s is a subpage" % a.title())
            continue
        if a.title() in cc:
            pywikibot.output(u"(cached) %s -> %s"%(a.title(), cc[a.title()]))
            continue
        if a.isRedirectPage():
            a=a.getRedirectTarget()
        try:
            if not a.exists():
                pywikibot.output(u"source page doesn't exist: %s" % a.title())
                continue
            atrans = findTranslated(a, tosite, quiet)
            if pType!='former':
                if atrans:
                    text=atrans.get()
                    m=re_Link_FA.search(text)
                    if m:
                        pywikibot.output(u"(already done)")
                    else:
                        # insert just before interwiki
                        if (not interactive or
                            pywikibot.input(
                                u'Connecting %s -> %s. Proceed? [Y/N]'
                                % (a.title(), atrans.title())) in ['Y','y']
                            ):
                            m=re_this_iw.search(text)
                            if not m:
                                pywikibot.output(
                                    u"no interwiki record, very strange")
                                continue
                            site = pywikibot.getSite()
                            comment = pywikibot.setAction(
                                i18n.twtranslate(
                                    site, 'featured-' + pType,
                                    {'page': a.title(
                                        asLink=True, forceInterwiki=True)}))
                            ### Moving {{Link FA|xx}} to top of interwikis ###
                            if template_on_top == True:
                                # Getting the interwiki
                                iw = pywikibot.getLanguageLinks(text, site)
                                # Removing the interwiki
                                text = pywikibot.removeLanguageLinks(text, site)
                                text += u"\r\n{{%s|%s}}\r\n" % (templatelist[0],
                                                                fromsite.lang)
                                # Adding the interwiki
                                text = pywikibot.replaceLanguageLinks(text,
                                                                      iw, site)

                            ### Placing {{Link FA|xx}} right next to corresponding interwiki ###
                            else:
                                text=(text[:m.end()]
                                      + (u" {{%s|%s}}" % (templatelist[0],
                                                          fromsite.lang))
                                      + text[m.end():])
                            if not dry:
                                try:
                                    atrans.put(text, comment)
                                except pywikibot.LockedPage:
                                    pywikibot.output(u'Page %s is locked!'
                                                     % atrans.title())
                    cc[a.title()]=atrans.title()
            else:
                if atrans:
                    text=atrans.get()
                    m=re_Link_FA.search(text)
                    if m:
                        # insert just before interwiki
                        if (not interactive or
                            pywikibot.input(
                                u'Connecting %s -> %s. Proceed? [Y/N]'
                                % (a.title(), atrans.title())) in ['Y','y']
                            ):
                            m=re_this_iw.search(text)
                            if not m:
                                pywikibot.output(
                                    u"no interwiki record, very strange")
                                continue
                            site = pywikibot.getSite()
                            comment = pywikibot.setAction(
                                i18n.twtranslate(
                                    site, 'featured-former',
                                    {'page': a.title(
                                        asLink=True, forceInterwiki=True)}))
                            text = re.sub(re_Link_FA,'',text)
                            if not dry:
                                try:
                                    atrans.put(text, comment)
                                except pywikibot.LockedPage:
#.........这里部分代码省略.........
开发者ID:moleculea,项目名称:ess,代码行数:101,代码来源:featured.py


示例12: str

# What follows is the main part of the code.
try:
    for pl in site.allpages(start):
        plname = pl.title()
        wikipedia.output(u'\nLoading %s...' % plname)
        try:
            oldtext = pl.get()
        except wikipedia.IsRedirectPage:
            wikipedia.output(u"%s is a redirect!" % plname)
            continue
        old = pl.interwiki()
        new = {}
        for pl2 in old:
            new[pl2.site()] = pl2
        newtext = wikipedia.replaceLanguageLinks(oldtext, new)
        if new:
            if oldtext != newtext:
                wikipedia.showDiff(oldtext, newtext)
                # Submit changes
                try:
                    status, reason, data = pl.put(newtext, comment=comm)
                    if str(status) != '302':
                        wikipedia.output(status, reason)
                except wikipedia.LockedPage:
                    wikipedia.output(u"%s is locked" % plname)
                    continue
            else:
                wikipedia.output(u'No changes needed.')
                continue
        else:
开发者ID:VisualEffects,项目名称:pywikia,代码行数:30,代码来源:standardize_interwiki.py


示例13: finish

    def finish(self, sa = None):
        """Round up the subject, making any necessary changes. This method
           should be called exactly once after the todo list has gone empty.

           This contains a shortcut: if a subject array is given in the argument
           sa, just before submitting a page change to the live wikipedia it is
           checked whether we will have to wait. If that is the case, the sa will
           be told to make another get request first."""
        if not self.isDone():
            raise "Bugcheck: finish called before done"
        if self.inpl.isRedirectPage():
            return
        if not self.untranslated and globalvar.untranslatedonly:
            return
        if len(self.done) == 1:
            # No interwiki at all
            return
        print "======Post-processing %s======"%(self.inpl.asasciilink())
        # Assemble list of accepted interwiki links
        if globalvar.autonomous:
            new = self.assemble()
            if new == None: # There are questions
                return
        else:
            new = self.assemble(returnonquestion = True)
            if new == None: # There are questions
                new = self.assemble(askall = True)
                if new == None:
                    return # User said give up
            
        print "==status=="
        old={}
        try:
            for pl in self.inpl.interwiki():
                old[pl.code()] = pl
        except wikipedia.NoPage:
            print "BUG:", self.inpl.asasciilink(), "No longer exists?"
        ####
        mods, removing = compareLanguages(old, new)
        if not mods and not globalvar.always:
            print "No changes needed"
            if globalvar.backlink:
                self.reportBacklinks(new)
        else:
            if mods:
                print "Changes to be made:",mods
            oldtext = self.inpl.get()
            newtext = wikipedia.replaceLanguageLinks(oldtext, new)
            if globalvar.debug:
                showDiff(oldtext, newtext)
            if newtext == oldtext:
                if globalvar.backlink:
                    self.reportBacklinks(new)
            else:
                print "NOTE: Replace %s" % self.inpl.asasciilink()
                if globalvar.forreal:
                    # Determine whether we need permission to submit
                    ask = False
                    if removing:
                        self.problem('removing: %s'%(",".join(removing)))
                        ask = True
                    if globalvar.force:
                        ask = False
                    if globalvar.confirm:
                        ask = True
                    # If we need to ask, do so
                    if ask:
                        if globalvar.autonomous:
                            # If we cannot ask, deny permission
                            answer = 'n'
                        else:
                            if globalvar.bell:
                                sys.stdout.write('\07')
                            answer = raw_input('submit y/n ?')
                    else:
                        # If we do not need to ask, allow
                        answer = 'y'
                    if answer == 'y':
                        # Check whether we will have to wait for wikipedia. If so, make
                        # another get-query first.
                        if sa:
                            while wikipedia.get_throttle.waittime() + 2.0 < wikipedia.put_throttle.waittime():
                                print "NOTE: Performing a recursive query first to save time...."
                                qdone = sa.oneQuery()
                                if not qdone:
                                    # Nothing more to do
                                    break
                        print "NOTE: Updating live wikipedia..."
                        status, reason, data = self.inpl.put(newtext,
                                                             comment='robot '+mods)
                        if str(status) != '302':
                            print status, reason
                        else:
                            if globalvar.backlink:
                                self.reportBacklinks(new)
开发者ID:karstenw,项目名称:Library,代码行数:95,代码来源:interwiki.py


示例14: standardizePageFooter


#.........这里部分代码省略.........
            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,
                                                  site=self.site)
        # Put the iw message back
        if not self.talkpage and \
           ((interwikiLinks or hasCommentLine) and
            self.site.language() == 'nn' or
            (interwikiLinks and hasCommentLine) and
            self.site.language() == 'fr'):
            text = text + '\r\n\r\n' + iw_msg
        # Adding stars templates
        if allstars:
            text = text.strip()+self.site.family.interwiki_text_separator
            allstars.sort()
            for element in allstars:
                text += '%s\r\n' % element.strip()
                if pywikibot.verbose:
                    pywikibot.output(u'%s' %element.strip())
        # Adding the interwiki
        if interwikiLinks:
            text = pywikibot.replaceLanguageLinks(text, interwikiLinks,
                                                  site=self.site,
                                                  template=self.template,
                                                  template_subpage=subpage)
        return text
开发者ID:Protonk,项目名称:pywikipedia2,代码行数:101,代码来源:cosmetic_changes.py


示例15: add_text


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python wikipedia.search函数代码示例发布时间:2022-05-26
下一篇:
Python wikipedia.replaceExcept函数代码示例发布时间: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