当前位置: 首页>>代码示例>>Python>>正文


Python wikipedia.translate函数代码示例

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


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

示例1: run

    def run(self):
        site = wikipedia.getSite()
        newCat = catlib.Category(site, 'Category:' + self.newCatTitle)

        # Copy the category contents to the new category page
        copied = False
        oldMovedTalk = None
        if self.oldCat.exists() and self.moveCatPage:
            copied = self.oldCat.copyAndKeep(
                            self.newCatTitle,
                            wikipedia.translate(site, cfd_templates))
            # Also move the talk page
            if copied:
                reason = wikipedia.translate(site, deletion_reason_move) \
                         % (self.newCatTitle, self.newCatTitle)
                oldTalk = self.oldCat.toggleTalkPage()
                if oldTalk.exists():
                    newTalkTitle = newCat.toggleTalkPage().title()
                    try:
                        talkMoved = oldTalk.move(newTalkTitle, reason)
                    except (wikipedia.NoPage, wikipedia.PageNotSaved), e:
                        #in order :
                        #Source talk does not exist, or
                        #Target talk already exists
                        wikipedia.output(e.message)
                    else:
                        if talkMoved:
                            oldMovedTalk = oldTalk
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:28,代码来源:category.py

示例2: run

 def run(self):
     mySite = wikipedia.getSite()
     while True:
         now = time.strftime("%d %b %Y %H:%M:%S (UTC)", time.gmtime())
         localSandboxTitle = wikipedia.translate(mySite, sandboxTitle)
         if type(localSandboxTitle) is list:
             titles = localSandboxTitle
         else:
             titles = [localSandboxTitle,]
         for title in titles:
             sandboxPage = wikipedia.Page(mySite, localSandboxTitle)
             try:
                 text = sandboxPage.get()
                 translatedContent = wikipedia.translate(mySite, content)
                 if text.strip() == translatedContent.strip():
                     wikipedia.output(u'The sandbox is still clean, no change necessary.')
                 else:
                     translatedMsg = wikipedia.translate(mySite, msg)
                     sandboxPage.put(translatedContent, translatedMsg)
             except wikipedia.EditConflict:
                 wikipedia.output(u'*** Loading again because of edit conflict.\n')
         if self.no_repeat:
             wikipedia.output(u'\nDone.')
             return
         else:
             wikipedia.output('\nSleeping %s hours, now %s' % (self.hours, now) )
             time.sleep(self.hours * 60 * 60)
开发者ID:pyropeter,项目名称:PyroBot-1G,代码行数:27,代码来源:clean_sandbox.py

示例3: treat

 def treat(self):
         page = pywikibot.Page(self.site, self.your_page)
         if page.exists():
             pywikibot.output(u'\nWikitable on \03{lightpurple}%s\03{default} will be completed with:\n' % self.your_page )
             text = page.get()
             newtext = self.newraw()
             pywikibot.output(newtext)
             choice = pywikibot.inputChoice(u'Do you want to add these on wikitable?', ['Yes', 'No'], ['y', 'N'], 'N')
             text = text[:-3] + newtext
             summ = pywikibot.translate(self.site, summary_update)
             if choice == 'y':
                 try:
                     page.put(u''.join(text), summ)
                 except:
                     pywikibot.output(u'Impossible to edit. It may be an edit conflict... Skipping...')
         else:
             pywikibot.output(u'\nWikitable on \03{lightpurple}%s\03{default} will be created with:\n' % self.your_page )
             newtext = self.newtable()+self.newraw()
             pywikibot.output(newtext)
             summ = pywikibot.translate(self.site, summary_creation)
             choice = pywikibot.inputChoice(u'Do you want to accept this page creation?', ['Yes', 'No'], ['y', 'N'], 'N')
             if choice == 'y':
                 try:
                     page.put(newtext, summ)
                 except pywikibot.LockedPage:
                     pywikibot.output(u"Page %s is locked; skipping." % title)
                 except pywikibot.EditConflict:
                     pywikibot.output(u'Skipping %s because of edit conflict' % title)
                 except pywikibot.SpamfilterError, error:
                     pywikibot.output(u'Cannot change %s because of spam blacklist entry %s' % (title, error.url))
开发者ID:NaturalSolutions,项目名称:ecoReleve-Concepts,代码行数:30,代码来源:statistics_in_wikitable.py

示例4: __init__

    def __init__(self, generator, oldImage, newImage=None, summary='',
                 always=False, loose=False):
        """
        Arguments:
            * generator - A page generator.
            * oldImage  - The title of the old image (without namespace)
            * newImage  - The title of the new image (without namespace), or
                          None if you want to remove the image.
        """
        self.generator = generator
        self.oldImage = oldImage
        self.newImage = newImage
        self.editSummary = summary
        self.summary = summary
        self.always = always
        self.loose = loose

        # get edit summary message
        mysite = pywikibot.getSite()
        if summary:
            self.editSummary = summary
        elif self.newImage:
            self.editSummary = (pywikibot.translate(mysite, self.msg_replace)
                                % (self.oldImage, self.newImage))
        else:
            self.editSummary = (pywikibot.translate(mysite, self.msg_remove)
                                % self.oldImage)
开发者ID:Rodehi,项目名称:GFROS,代码行数:27,代码来源:image.py

示例5: run

    def run(self):
        site = pywikibot.getSite()
        newCat = catlib.Category(site, self.newCatTitle)
        # set edit summary message
        if not self.editSummary:
            try:
                self.editSummary = pywikibot.translate(site, msg_change) % (self.oldCat.title(), newCat.title() )
            except TypeError:
                self.editSummary = pywikibot.translate(site, msg_change) % self.oldCat.title()

        # Copy the category contents to the new category page
        copied = False
        oldMovedTalk = None
        if self.oldCat.exists() and self.moveCatPage:
            copied = self.oldCat.copyAndKeep(
                            self.newCatTitle,
                            pywikibot.translate(site, cfd_templates))
            # Also move the talk page
            if copied:
                reason = pywikibot.translate(site, deletion_reason_move) \
                         % (self.newCatTitle, self.newCatTitle)
                oldTalk = self.oldCat.toggleTalkPage()
                if oldTalk.exists():
                    newTalkTitle = newCat.toggleTalkPage().title()
                    try:
                        talkMoved = oldTalk.move(newTalkTitle, reason)
                    except (pywikibot.NoPage, pywikibot.PageNotSaved), e:
                        #in order :
                        #Source talk does not exist, or
                        #Target talk already exists
                        pywikibot.output(e.message)
                    else:
                        if talkMoved:
                            oldMovedTalk = oldTalk
开发者ID:yknip1207,项目名称:genewiki,代码行数:34,代码来源:category.py

示例6: guessReasonForDeletion

    def guessReasonForDeletion(self, page):
        reason = None
        # TODO: The following check loads the page 2 times. Find a better way to
        # do it.
        if page.isTalkPage() and (page.toggleTalkPage().isRedirectPage() or not page.toggleTalkPage().exists()):
            # This is probably a talk page that is orphaned because we
            # just deleted the associated article.
            reason = pywikibot.translate(self.mySite, self.talk_deletion_msg)
        else:
            # Try to guess reason by the template used
            templateNames = page.templates()
            reasons = pywikibot.translate(self.mySite, self.deletion_messages)

            for templateName in templateNames:
                if templateName in reasons:
                    if type(reasons[templateName]) is not unicode:
                        # Make alias to delete_reasons
                        reason = pywikibot.translate(self.mySite, self.delete_reasons)[reasons[templateName]]
                    else:
                        reason = reasons[templateName]
                    break
        if not reason:
            # Unsuccessful in guessing the reason. Use a default message.
            reason = reasons[u"_default"]
        return reason
开发者ID:valhallasw,项目名称:pwb-test-alpha,代码行数:25,代码来源:speedy_delete.py

示例7: get_wiki_save_page

def get_wiki_save_page(stat_page=False):

    site = pywikibot.getSite()
    wiki_save_path = {
        '_default': u'User:%s/Report' % config.usernames[
            site.family.name][site.lang],
        'es': u'Usuario:%s/Reporte' % config.usernames[
            site.family.name][site.lang],
        'it': u'Utente:RevertBot/Report'
    }

    save_path = pywikibot.translate(site, wiki_save_path)
    if stat_page:
        return pywikibot.Page(site,
                              '%s/%s' % (save_path,
                                         pywikibot.translate(site,
                                                             stat_msg)[0]))
    if append_date_to_wiki_save_path:
        t = time.localtime()
        day = ''
        if append_day_to_wiki_save_path:
            day = '_' + str(t[2])
        save_path += '%s_%s_%s' % (day, date.monthName(site.language(), t[1]),
                                   str(t[0]))
    return pywikibot.Page(site, save_path)
开发者ID:fdeco,项目名称:pywikibot-compat,代码行数:25,代码来源:copyright_put.py

示例8: main

def main():
    global always
    always = False

    for arg in pywikibot.handleArgs():
        if arg == '-always':
            always = True

    mysite = pywikibot.getSite()
    # If anything needs to be prepared, you can do it here
    template_image = pywikibot.translate(pywikibot.getSite(),
                                         template_to_the_image)
    template_user = pywikibot.translate(pywikibot.getSite(),
                                        template_to_the_user)
    except_text_translated = pywikibot.translate(pywikibot.getSite(),
                                                 except_text)
    basicgenerator = pagegenerators.UnusedFilesGenerator()
    generator = pagegenerators.PreloadingGenerator(basicgenerator)
    for page in generator:
        pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                         % page.title())
        if except_text_translated not in page.getImagePageHtml() and \
           'http://' not in page.get():
            pywikibot.output(u'\n' + page.title())
            if template_image in page.get():
                pywikibot.output(u"%s done already" % page.aslink())
                continue
            appendtext(page, u"\n\n"+template_image)
            uploader = page.getFileVersionHistory().pop()[1]
            usertalkname = u'User Talk:%s' % uploader
            usertalkpage = pywikibot.Page(mysite, usertalkname)
            msg2uploader = template_user % {'title': page.title()}
            appendtext(usertalkpage, msg2uploader)
开发者ID:SASfit,项目名称:SASfit,代码行数:33,代码来源:unusedfiles.py

示例9: treat

 def treat(self):
     page = wikipedia.Page(self.site, self.your_page)
     if page.exists():
         wikipedia.output(
             u"\nWikitable on \03{lightpurple}%s\03{default} will be completed with:\n" % self.your_page
         )
         text = page.get()
         newtext = self.newraw()
         wikipedia.output(newtext)
         choice = wikipedia.inputChoice(u"Do you want to add these on wikitable?", ["Yes", "No"], ["y", "N"], "N")
         text = text[:-3] + newtext
         summ = wikipedia.translate(self.site, summary_update)
         if choice == "y":
             try:
                 page.put(u"".join(text), summ)
             except:
                 wikipedia.output(u"Impossible to edit. It may be an edit conflict... Skipping...")
     else:
         wikipedia.output(u"\nWikitable on \03{lightpurple}%s\03{default} will be created with:\n" % self.your_page)
         newtext = self.newtable() + self.newraw()
         wikipedia.output(newtext)
         summ = wikipedia.translate(self.site, summary_creation)
         choice = wikipedia.inputChoice(u"Do you want to accept this page creation?", ["Yes", "No"], ["y", "N"], "N")
         if choice == "y":
             try:
                 page.put(newtext, summ)
             except wikipedia.LockedPage:
                 wikipedia.output(u"Page %s is locked; skipping." % title)
             except wikipedia.EditConflict:
                 wikipedia.output(u"Skipping %s because of edit conflict" % title)
             except wikipedia.SpamfilterError, error:
                 wikipedia.output(u"Cannot change %s because of spam blacklist entry %s" % (title, error.url))
开发者ID:yknip1207,项目名称:genewiki,代码行数:32,代码来源:statistics_in_wikitable.py

示例10: setSummaryMessage

    def setSummaryMessage(self, disambPage, new_targets=[], unlink=False,
                          dn=False):
        # make list of new targets
        targets = ''
        for page_title in new_targets:
            targets += u'[[%s]], ' % page_title
        # remove last comma
        targets = targets[:-2]

        if not targets:
            targets = i18n.twtranslate(self.mysite,
                                       unknown_msg)

        # first check whether user has customized the edit comment
        if (self.mysite.family.name in pywikibot.config.disambiguation_comment
            and self.mylang in
                pywikibot.config.disambiguation_comment[
                    self.mysite.family.name]):
            try:
                self.comment = pywikibot.translate(
                    self.mysite,
                    pywikibot.config.disambiguation_comment[
                        self.mysite.family.name]) % (disambPage.title(),
                                                     targets)
            # Backwards compatibility, type error probably caused by too
            # many arguments for format string
            except TypeError:
                self.comment = pywikibot.translate(
                    self.mysite,
                    pywikibot.config.disambiguation_comment[
                        self.mysite.family.name]) % disambPage.title()
        elif disambPage.isRedirectPage():
            # when working on redirects, there's another summary message
            if unlink and not new_targets:
                self.comment = i18n.twtranslate(self.mysite,
                                                msg_redir_unlink,
                                                {'from': disambPage.title()})
            elif dn and not new_targets:
                self.comment = i18n.twtranslate(
                    self.mysite,
                    msg_redir_dn,
                    {'from': disambPage.title()})
            else:
                self.comment = i18n.twtranslate(self.mysite,
                                                msg_redir,
                                                {'from': disambPage.title(),
                                                 'to': targets})
        else:
            if unlink and not new_targets:
                self.comment = i18n.twtranslate(self.mysite, msg_unlink,
                                                {'from': disambPage.title()})
            elif dn and not new_targets:
                self.comment = i18n.twtranslate(self.mysite, msg_dn,
                                                {'from': disambPage.title()})
            else:
                self.comment = i18n.twtranslate(self.mysite, msg,
                                                {'from': disambPage.title(),
                                                 'to': targets})
开发者ID:Rodehi,项目名称:GFROS,代码行数:58,代码来源:solve_disambiguation.py

示例11: transferImage

    def transferImage(self, sourceImagePage, debug=False):
        """Gets a wikilink to an image, downloads it and its description,
           and uploads it to another wikipedia.
           Returns the filename which was used to upload the image
           This function is used by imagetransfer.py and by copy_table.py
        """
        sourceSite = sourceImagePage.site()
        if debug: print "-" * 50
        if debug: print "Found image: %s"% imageTitle
        url = sourceImagePage.fileUrl()
        newname = sourceImagePage.titleWithoutNamespace()
        pywikibot.output(u"URL should be: %s" % url)
        # localize the text that should be printed on the image description page
        try:
            description = sourceImagePage.get()
            #unlink categories
            #description = pywikibot.removeCategoryLinks(description,pywikibot.getSite('commons', 'commons'))
            description = re.sub(u'\[\[Category', u'[[:Category', description, flags=re.IGNORECASE)
            # try to translate license templates
            if (sourceSite.sitename(), self.targetSite.sitename()) in licenseTemplates:
                for old, new in licenseTemplates[(sourceSite.sitename(), self.targetSite.sitename())].iteritems():
                    new = '{{%s}}' % new
                    old = re.compile('{{%s}}' % old)
                    description = pywikibot.replaceExcept(description, old, new,
                                                          ['comment', 'math',
                                                           'nowiki', 'pre'])

            description = pywikibot.translate(self.targetSite, copy_message) \
                          % (sourceSite, description)
            description += '\n\n' + sourceImagePage.getFileVersionHistoryTable()
            # add interwiki link
            if sourceSite.family == self.targetSite.family:
                description += "\r\n\r\n" + sourceImagePage.aslink(forceInterwiki = True)
            #add cat
            description += "\n[[Kategooria:Commonsist kopeeritud pildid]]\n"
        except pywikibot.NoPage:
            description=''
            print "Image does not exist or description page is empty."
        except pywikibot.IsRedirectPage:
            description=''
            print "Image description page is redirect."
        else:
            #bot = UploadRobot(url=self.imagePage.fileUrl(), description=CH, useFilename=self.newname, keepFilename=True, verifyDescription=False, ignoreWarning = True, targetSite = pywikibot.getSite('commons', 'commons'))
            
            bot = upload.UploadRobot(url = url, description = description, useFilename = newname, keepFilename=True, verifyDescription=False, ignoreWarning = False, targetSite = self.targetSite)
            # try to upload
            targetFilename = bot.run()
            if targetFilename and self.targetSite.family.name == 'commons' and self.targetSite.lang == 'commons':
                # upload to Commons was successful
                reason = pywikibot.translate(sourceSite, nowCommonsMessage)
                # try to delete the original image if we have a sysop account
                if sourceSite.family.name in config.sysopnames and sourceSite.lang in config.sysopnames[sourceSite.family.name]:
                    if sourceImagePage.delete(reason):
                        return
                if sourceSite.lang in nowCommonsTemplate and sourceSite.family.name in config.usernames and sourceSite.lang in config.usernames[sourceSite.family.name]:
                    # add the nowCommons template.
                    pywikibot.output(u'Adding nowCommons template to %s' % sourceImagePage.title())
                    sourceImagePage.put(sourceImagePage.get() + '\n\n' + nowCommonsTemplate[sourceSite.lang] % targetFilename, comment = nowCommonsMessage[sourceSite.lang])
开发者ID:edgarskos,项目名称:Toolserver-bots,代码行数:58,代码来源:myimagetransfer.py

示例12: run

    def run(self):
        def minutesDiff(time1, time2):
            if type(time1) is long:
                time1 = str(time1)
            if type(time2) is long:
                time2 = str(time2)
            t1 = (((int(time1[0:4]) * 12 + int(time1[4:6])) * 30 + int(time1[6:8])) * 24 + int(time1[8:10]) * 60) + int(
                time1[10:12]
            )
            t2 = (((int(time2[0:4]) * 12 + int(time2[4:6])) * 30 + int(time2[6:8])) * 24 + int(time2[8:10]) * 60) + int(
                time2[10:12]
            )
            return abs(t2 - t1)

        mySite = pywikibot.getSite()
        while True:
            wait = False
            now = time.strftime("%d %b %Y %H:%M:%S (UTC)", time.gmtime())
            localSandboxTitle = pywikibot.translate(mySite, sandboxTitle)
            if type(localSandboxTitle) is list:
                titles = localSandboxTitle
            else:
                titles = [localSandboxTitle]
            for title in titles:
                sandboxPage = pywikibot.Page(mySite, title)
                try:
                    text = sandboxPage.get()
                    translatedContent = pywikibot.translate(mySite, content)
                    translatedMsg = pywikibot.translate(mySite, msg)
                    subst = "subst:" in translatedContent
                    if text.strip() == translatedContent.strip():
                        pywikibot.output(u"The sandbox is still clean, no change necessary.")
                    elif subst and sandboxPage.userName() == mySite.loggedInAs():
                        pywikibot.output(u"The sandbox might be clean, no change necessary.")
                    elif text.find(translatedContent.strip()) <> 0 and not subst:
                        sandboxPage.put(translatedContent, translatedMsg)
                        pywikibot.output(u"Standard content was changed, sandbox cleaned.")
                    else:
                        diff = minutesDiff(sandboxPage.editTime(), time.strftime("%Y%m%d%H%M%S", time.gmtime()))
                        # Is the last edit more than 5 minutes ago?
                        if diff >= self.delay:
                            sandboxPage.put(translatedContent, translatedMsg)
                        else:  # wait for the rest
                            pywikibot.output(u"Sleeping for %d minutes." % (self.delay - diff))
                            time.sleep((self.delay - diff) * 60)
                            wait = True
                except pywikibot.EditConflict:
                    pywikibot.output(u"*** Loading again because of edit conflict.\n")
            if self.no_repeat:
                pywikibot.output(u"\nDone.")
                return
            elif not wait:
                if self.hours < 1.0:
                    pywikibot.output("\nSleeping %s minutes, now %s" % ((self.hours * 60), now))
                else:
                    pywikibot.output("\nSleeping %s hours, now %s" % (self.hours, now))
                time.sleep(self.hours * 60 * 60)
开发者ID:yknip1207,项目名称:genewiki,代码行数:57,代码来源:clean_sandbox.py

示例13: run

    def run(self):
        while not self.killed:
            if len(self.queue) == 0:
                if self.finishing:
                    break
                else:
                    time.sleep(0.1)
            else:
                self.semaphore.acquire()
                (url, errorReport, containingPage, archiveURL) = self.queue[0]
                self.queue = self.queue[1:]
                talkPage = containingPage.toggleTalkPage()
                pywikibot.output(
                    u'\03{lightaqua}** Reporting dead link on %s...\03{default}'
                    % talkPage.title(asLink=True))
                try:
                    content = talkPage.get() + "\n\n"
                    if url in content:
                        pywikibot.output(
                            u'\03{lightaqua}** Dead link seems to have already been reported on %s\03{default}'
                            % talkPage.title(asLink=True))
                        self.semaphore.release()
                        continue
                except (pywikibot.NoPage, pywikibot.IsRedirectPage):
                    content = u''

                if archiveURL:
                    archiveMsg = pywikibot.translate(pywikibot.getSite(),
                                                     talk_report_archive) % archiveURL
                else:
                    archiveMsg = u''
                # The caption will default to "Dead link". But if there is
                # already such a caption, we'll use "Dead link 2",
                # "Dead link 3", etc.
                caption = pywikibot.translate(pywikibot.getSite(),
                                              talk_report_caption)
                i = 1
                # Check if there is already such a caption on the talk page.
                while re.search('= *' + caption + ' *=', content) is not None:
                    i += 1
                    caption = pywikibot.translate(pywikibot.getSite(),
                                                  talk_report_caption) + " " + str(i)
                content += pywikibot.translate(pywikibot.getSite(),
                                               talk_report) % (caption,
                                                               errorReport,
                                                               archiveMsg)
                comment = u'[[%s#%s|→]]%s' % (talkPage.title(), caption,
                                              pywikibot.translate(pywikibot.getSite(),
                                                                  talk_report_msg))
                try:
                    talkPage.put(content, comment)
                except pywikibot.SpamfilterError, error:
                    pywikibot.output(
                        u'\03{lightaqua}** SpamfilterError while trying to change %s: %s\03{default}'
                        % (talkPage.title(asLink=True), error.url))

                self.semaphore.release()
开发者ID:dbow,项目名称:Project-OPEN,代码行数:57,代码来源:weblinkchecker.py

示例14: reportBadAccount

    def reportBadAccount(self, name=None, final=False):
        # Queue process
        if name:
            if globalvar.confirm:
                answer = wikipedia.inputChoice(
                    u"%s may have an unwanted username, do you want to report this user?" % name,
                    ["Yes", "No", "All"],
                    ["y", "N", "a"],
                    "N",
                )
                if answer in ["a", "all"]:
                    answer = "y"
                    globalvar.confirm = False
            else:
                answer = "y"

            if answer.lower() in ["yes", "y"] or not globalvar.confirm:
                showStatus()
                wikipedia.output(u"%s is possibly an unwanted username. It will be reported." % name)
                if hasattr(self, "_BAQueue"):
                    self._BAQueue.append(name)
                else:
                    self._BAQueue = [name]

        if len(self._BAQueue) >= globalvar.dumpToLog or final:
            rep_text = ""
            # name in queue is max, put detail to report page
            wikipedia.output("Updating badname accounts to report page...")
            rep_page = wikipedia.Page(self.site, wikipedia.translate(self.site, report_page))
            if rep_page.exists():
                text_get = rep_page.get()
            else:
                text_get = u"This is a report page for the Bad-username, please translate me. --~~~"
            pos = 0
            # The talk page includes "_" between the two names, in this way i replace them to " ".
            for usrna in self._BAQueue:
                username = wikipedia.url2link(usrna, self.site, self.site)
                n = re.compile(re.escape(username), re.UNICODE)
                y = n.search(text_get, pos)
                if y:
                    wikipedia.output(u"%s is already in the report page." % username)
                else:
                    # Adding the log.
                    rep_text += wikipedia.translate(self.site, report_text) % username
                    if self.site.lang == "it":
                        rep_text = "%s%s}}" % (rep_text, self.bname[username])

            com = wikipedia.translate(self.site, comment)
            if rep_text != "":
                rep_page.put(text_get + rep_text, comment=com, minorEdit=True)
                showStatus(5)
                wikipedia.output(u"Reported")
            self.BAQueue = list()
        else:
            return True
开发者ID:dantman,项目名称:pywikia,代码行数:55,代码来源:welcome.py

示例15: put

    def put(self, title, contents):
        mysite = wikipedia.getSite()

        page = wikipedia.Page(mysite, title)
        # Show the title of the page we're working on.
        # Highlight the title in purple.
        wikipedia.output(u">>> \03{lightpurple}%s\03{default} <<<" % page.title())

        if self.summary:
            comment = self.summary
        else:
            comment = wikipedia.translate(mysite, self.msg)

        comment_top = comment + " - " + wikipedia.translate(mysite, self.msg_top)
        comment_bottom = comment + " - " + wikipedia.translate(mysite, self.msg_bottom)
        comment_force = comment + " *** " + wikipedia.translate(mysite, self.msg_force) + " ***"

        # Remove trailing newlines (cause troubles when creating redirects)
        contents = re.sub('^[\r\n]*','', contents)

        if page.exists():
            if self.append == "Top":
                wikipedia.output(u"Page %s already exists, appending on top!" % title)
                contents = contents + page.get()
                comment = comment_top
            elif self.append == "Bottom":
                wikipedia.output(u"Page %s already exists, appending on bottom!" % title)
                contents = page.get() + contents
                comment = comment_bottom
            elif self.force:
                wikipedia.output(u"Page %s already exists, ***overwriting!" % title)
                comment = comment_force
            else:
                wikipedia.output(u"Page %s already exists, not adding!" % title)
                return
        else:
           if self.autosummary:
                comment = ''
                wikipedia.setAction('')

        if self.dry:
            wikipedia.output("*** Dry mode ***\n" + \
                "\03{lightpurple}title\03{default}: " + title + "\n" + \
                "\03{lightpurple}contents\03{default}:\n" + contents + "\n" \
                "\03{lightpurple}comment\03{default}: " + comment + "\n")
            return

        try:
            page.put(contents, comment = comment, minorEdit = self.minor)
        except wikipedia.LockedPage:
            wikipedia.output(u"Page %s is locked; skipping." % title)
        except wikipedia.EditConflict:
            wikipedia.output(u'Skipping %s because of edit conflict' % title)
        except wikipedia.SpamfilterError, error:
            wikipedia.output(u'Cannot change %s because of spam blacklist entry %s' % (title, error.url))
开发者ID:VisualEffects,项目名称:pywikia,代码行数:55,代码来源:pagefromfile.py


注:本文中的wikipedia.translate函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。