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

Python pywikibot.inputChoice函数代码示例

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

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



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

示例1: 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 " u"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 " u"edit conflict. Skipping...")
     else:
         pywikibot.output(
             u"\nWikitable on \03{lightpurple}%s\03{default} will be " u"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 " u"blacklist entry %s" % (title, error.url))
开发者ID:hroest,项目名称:pywikibot-compat,代码行数:34,代码来源:statistics_in_wikitable.py


示例2: creerPage

	def creerPage(self, text, page, comment, minorEdit=True, botflag=True):
		# only save if something was changed
		if text != None:
			arretdurgence()
			# 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())
			# show what was changed
			#pywikibot.showDiff(page.get(), text)
			pywikibot.output(u'%s' % text)
			pywikibot.output(u'Comment: %s' %comment)
			if not self.dry:
				#choice = pywikibot.inputChoice(u'Êtes-vous sûr de vouloir créer la page ?', ['Yes', 'No'], ['y', 'N'], 'N')
				choice = 'y'
				if choice == 'y':
					try:
						arretdurgence()
						if arret == "Oui":
							pywikibot.inputChoice(u"Demande d'arrêt d'urgence",['vu'],['v'],'')
						# Save the page
						page.put(text, comment=comment,
								 minorEdit=minorEdit, botflag=botflag)
					except pywikibot.LockedPage:
						pywikibot.output(u"Page %s is locked; skipping."
										 % page.title(asLink=True))
					except pywikibot.EditConflict:
						pywikibot.output(
							u'Skipping %s because of edit conflict'
							% (page.title()))
					except pywikibot.SpamfilterError, error:
						pywikibot.output(
u'Cannot change %s because of spam blacklist entry %s'
							% (page.title(), error.url))
					else:
						return True
开发者ID:Toto-Azero,项目名称:Wikipedia,代码行数:35,代码来源:random_pages_portails.py


示例3: process_filename

    def process_filename(self):
        """Return base filename portion of self.url"""
        # Isolate the pure name
        filename = self.url
        # Filename may be either a local file path or a URL
        if "://" in filename:
            # extract the path portion of the URL
            filename = urlparse.urlparse(filename).path
        filename = os.path.basename(filename)

        if self.useFilename:
            filename = self.useFilename
        if not self.keepFilename:
            pywikibot.output(
                u"The filename on the target wiki will default to: %s"
                % filename)
            # FIXME: these 2 belong somewhere else, presumably in family
            forbidden = '/' # to be extended
            allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi',
                               u'ogg', u'png', u'svg', u'xcf', u'djvu')
            # ask until it's valid
            while True:
                newfn = pywikibot.input(
                            u'Enter a better name, or press enter to accept:')
                if newfn == "":
                    newfn = filename
                    break
                ext = os.path.splitext(newfn)[1].lower().strip('.')
                # are any chars in forbidden also in newfn?
                invalid = set(forbidden) & set(newfn)
                if invalid:
                    c = "".join(invalid)
                    print "Invalid character(s): %s. Please try again" % c
                    continue
                if ext not in allowed_formats:
                    choice = pywikibot.inputChoice(
                        u"File format is not one of [%s], but %s. Continue?"
                         % (u' '.join(allowed_formats), ext),
                            ['yes', 'no'], ['y', 'N'], 'N')
                    if choice == 'n':
                        continue
                break
            if newfn != '':
                filename = newfn
        # A proper description for the submission.
        pywikibot.output(u"The suggested description is:")
        pywikibot.output(self.description)
        if self.verifyDescription:
            newDescription = u''
            choice = pywikibot.inputChoice(
                u'Do you want to change this description?',
                ['Yes', 'No'], ['y', 'N'], 'n')
            if choice == 'y':
                import editarticle
                editor = editarticle.TextEditor()
                newDescription = editor.edit(self.description)
            # if user saved / didn't press Cancel
            if newDescription:
                self.description = newDescription
        return filename
开发者ID:azatoth,项目名称:pywikipedia,代码行数:60,代码来源:upload.py


示例4: useHashGenerator

 def useHashGenerator(self):
     # http://toolserver.org/~multichill/nowcommons.php?language=it&page=2&filter=
     lang = self.site.lang
     num_page = 0
     word_to_skip_translated = i18n.translate(self.site, word_to_skip)
     images_processed = list()
     while 1:
         url = ('http://toolserver.org/~multichill/nowcommons.php?'
                'language=%s&page=%s&filter=') % (lang, num_page)
         HTML_text = self.site.getUrl(url, no_hostname=True)
         reg = r'<[Aa] href="(?P<urllocal>.*?)">(?P<imagelocal>.*?)</[Aa]> +?</td><td>\n\s*?'
         reg += r'<[Aa] href="(?P<urlcommons>http://commons.wikimedia.org/.*?)" \
                >Image:(?P<imagecommons>.*?)</[Aa]> +?</td><td>'
         regex = re.compile(reg, re.UNICODE)
         found_something = False
         change_page = True
         for x in regex.finditer(HTML_text):
             found_something = True
             image_local = x.group('imagelocal')
             image_commons = x.group('imagecommons')
             if image_local in images_processed:
                 continue
             change_page = False
             images_processed.append(image_local)
             # Skip images that have something in the title (useful for it.wiki)
             image_to_skip = False
             for word in word_to_skip_translated:
                 if word.lower() in image_local.lower():
                     image_to_skip = True
             if image_to_skip:
                 continue
             url_local = x.group('urllocal')
             url_commons = x.group('urlcommons')
             pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                              % image_local)
             pywikibot.output(u'Local: %s\nCommons: %s\n'
                              % (url_local, url_commons))
             result1 = webbrowser.open(url_local, 0, 1)
             result2 = webbrowser.open(url_commons, 0, 1)
             if image_local.split('Image:')[1] == image_commons:
                 choice = pywikibot.inputChoice(
                     u'The local and the commons images have the same name, continue?',
                     ['Yes', 'No'], ['y', 'N'], 'N')
             else:
                 choice = pywikibot.inputChoice(
                     u'Are the two images equal?',
                     ['Yes', 'No'], ['y', 'N'], 'N')
             if choice.lower() in ['y', 'yes']:
                 yield [image_local, image_commons]
             else:
                 continue
         # The page is dinamically updated, so we may don't need to change it
         if change_page:
             num_page += 1
         # If no image found means that there aren't anymore, break.
         if not found_something:
             break
开发者ID:bjonesin,项目名称:pywikibot-core,代码行数:57,代码来源:nowcommons.py


示例5: reportBadAccount

    def reportBadAccount(self, name=None, final=False):
        #Queue process
        if name:
            if globalvar.confirm:
                answer = pywikibot.inputChoice(
                    u'%s may have an unwanted username, do you want to report '
                    u'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()
                pywikibot.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
            pywikibot.output("Updating badname accounts to report page...")
            rep_page = pywikibot.Page(self.site,
                                      pywikibot.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 = pywikibot.url2link(usrna, self.site, self.site)
                n = re.compile(re.escape(username), re.UNICODE)
                y = n.search(text_get, pos)
                if y:
                    pywikibot.output(u'%s is already in the report page.'
                                     % username)
                else:
                    # Adding the log.
                    rep_text += pywikibot.translate(self.site, report_text) % username
                    if self.site.code == 'it':
                        rep_text = "%s%s}}" % (rep_text, self.bname[username])

            com = i18n.twtranslate(self.site, 'welcome-bad_username')
            if rep_text != '':
                rep_page.put(text_get + rep_text, comment=com, force=True,
                             minorEdit=True)
                showStatus(5)
                pywikibot.output(u'Reported')
            self.BAQueue = list()
        else:
            return True
开发者ID:octobertech,项目名称:pywikibot-core,代码行数:60,代码来源:welcome.py


示例6: save

   def save(self, text, page, comment=None, minorEdit=True,
             botflag=True):
      # only save if something was changed
      saveres=False
      if self.text != text:
         if not self.dry:
            if self.manual:
               # 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())
               # show what was changed
               pywikibot.showDiff(page.get(), text)
               logger.info(u'Comment: %s' %comment)
   
               choice = pywikibot.inputChoice(
                       u'Do you want to accept these changes?',
                       ['Yes', 'No'], ['y', 'N'], 'N')
   
            if (not self.manual) or (self.manual and choice == 'y'):
               logger.debug("Saving ...")
               saveres=self._save(page,text,comment,minorEdit,botflag)
            else:
               logger.debug("Changes discarded - doing nothing")
      else:
         logger.debug("Nothing changed - doing nothing")

      if saveres:
         logger.info("Changes saved")
      else:
         logger.info("Nothing done")

      return saveres
开发者ID:CristianCantoro,项目名称:rcantorobot,代码行数:33,代码来源:sbbot.py


示例7: treat

 def treat(self, page):
     try:
         # 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())
         ccToolkit = CosmeticChangesToolkit(
             page.site, debug=True, namespace=page.namespace(), pageTitle=page.title()
         )
         changedText = ccToolkit.change(page.get())
         if changedText.strip() != page.get().strip():
             if not self.acceptall:
                 choice = pywikibot.inputChoice(
                     u"Do you want to accept these changes?", ["Yes", "No", "All", "Quit"], ["y", "N", "a", "q"], "N"
                 )
                 if choice == "a":
                     self.acceptall = True
                 elif choice == "q":
                     self.done = True
                     return
             if self.acceptall or choice == "y":
                 page.text = changedText
                 page.save(comment=self.comment, async=self.async)
         else:
             pywikibot.output("No changes were necessary in %s" % page.title())
     except pywikibot.NoPage:
         pywikibot.output("Page %s does not exist?!" % page.title(asLink=True))
     except pywikibot.IsRedirectPage:
         pywikibot.output("Page %s is a redirect; skipping." % page.title(asLink=True))
     except pywikibot.LockedPage:
         pywikibot.output("Page %s is locked?!" % page.title(asLink=True))
     except pywikibot.EditConflict:
         pywikibot.output("An edit conflict has occured at %s." % page.title(asLink=True))
开发者ID:reza1615,项目名称:pywikipedia-rewrite,代码行数:32,代码来源:cosmetic_changes.py


示例8: delete_item

def delete_item(item, other, msg=None, by=site.user(), rfd=False, allow_sitelinks=False, askmerge=False):
    item.get(force=True)
    other.get(force=True)
    if allow_sitelinks is not True and len(item.sitelinks) > 0:
        error_merge_msg(item, other)
        return False
    if compare(item, other, 'sitelinks') is False or compare(item, other, 'labels') is False or compare(item, other, 'descriptions') is False:
        if askmerge and pywikibot.inputChoice(u'force merging?', ['Yes', 'No'], ['Y', 'N'], 'N').strip().lower() in ['yes', 'y']:
            merge_items((other, item), force_lower=False, taxon_mode=False)
        return False
    if by is None:
        by = item.site.data_repository().user()
    for key in item.aliases:
        for alias in item.aliases[key]:
            if alias.strip() != '' and ((key not in other.aliases) or (alias not in other.aliases[key])):
                error_merge_msg(item, other)
                return False
    for prop in item.claims:
        if (prop not in other.claims) or len(list(set([claim.getTarget() for claim in item.claims[prop]])-set([claim.getTarget() for claim in other.claims[prop]]))):
            error_merge_msg(item, other)
            return False
    if rfd:
        rfd_page = pywikibot.Page(site, 'Requests for deletions', ns=4)
        rfd_page.get(force=True)
        if msg is None:
            msg = u'Merged with {other}{by}'.format(other=other.getID(), by=(u' by [[User:{0}|{0}]]'.format(by) if by != site.user() else ''))
        rfd_page.text += u'\n\n{{{{subst:Request for deletion|itemid={qid}|reason={msg}}}}} --~~~~'.format(qid=item.getID(), msg=msg)
        page.save(comment=u'[[Wikidata:Bots|Bot]]: nominating [[{qid}]] for deletion'.format(qid=item.getID()), minor=False, botflag=True)
        pywikibot.output(u'\03{{lightgreen}}{item} successfully nominated for deletion'.format(item=item))
        return True
    else:
        item.delete(reason=(msg if msg else u'Merged with [[{qid}]] by [[User:{by}|{by}]]'.format(qid=other.getID(), by=by)))
        pywikibot.output(u'\03{{lightgreen}}{item} successfully deleted'.format(item=item))
        return True
开发者ID:edgarskos,项目名称:wiki,代码行数:34,代码来源:merge.py


示例9: check_protection_level

def check_protection_level(operation, level, levels, default=None):
    """Check if the protection level is valid or asks if necessary.

    @return a valid protection level
    @rtype string
    """
    if level not in levels:
        first_char = []
        default_char = None
        num = 1
        for level in levels:
            for c in level:
                if c not in first_char:
                    first_char.append(c)
                    break
            else:
                first_char.append(unicode(num))
                num += 1
            if level == default:
                default_char = first_char[-1]
        choice = pywikibot.inputChoice('Choice a protection level to %s:'
                                       % operation, levels, first_char,
                                       default=default_char)

        return levels[first_char.index(choice)]
    else:
        return level
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:27,代码来源:protect.py


示例10: get_dest

 def get_dest(self):
     self.dest = u'%s-core.%s' % tuple(self.source.rsplit(u'.', 1))
     if not self.warnonly and pywikibot.inputChoice(
             u'Destination file is %s.' % self.dest,
             ['Yes', 'No'], ['y', 'n'], 'y') == 'n':
         pywikibot.output('Quitting...')
         exit()
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:7,代码来源:compat2core.py


示例11: save

    def save(self, page, newText):
        """
        Saves the page to the wiki, if the user accepts the changes made.
        """
        pywikibot.showDiff(page.get(), newText)
        if not self.always:
            choice = pywikibot.inputChoice(
                u'Do you want to accept these changes?',
                ['Yes', 'No', 'Always yes'], 'yNa', 'Y')
            if choice == 'n':
                return
            elif choice == 'a':
                self.always = True

        page.text = newText
        if self.always:
            try:
                page.save(self.comment)
            except pywikibot.EditConflict:
                pywikibot.output(u'Skipping %s because of edit conflict'
                                 % (page.title(),))
            except pywikibot.SpamfilterError as e:
                pywikibot.output(
                    u'Cannot change %s because of blacklist entry %s'
                    % (page.title(), e.url))
            except pywikibot.LockedPage:
                pywikibot.output(u'Skipping %s (locked page)' % (page.title(),))
        else:
            # Save the page in the background. No need to catch exceptions.
            page.save(self.comment, async=True)
开发者ID:legoktm,项目名称:pywikibot-core,代码行数:30,代码来源:noreferences.py


示例12: wait_completion

    def wait_completion(self):
        """Pending threads finish."""
        def remaining():
            remainingItems = self.pool.qsize() - 1
                # -1 because we added a None element to stop the queue
            remainingSeconds = ltime.td(seconds=remainingItems)
            return (remainingItems, remainingSeconds)

        self.pool.put((None, [], {}))

        if self.pool.qsize() > 1:
            pywikibot.output(u'Waiting for %i items to be put. Estimated time remaining: %s'
                   % remaining())

        while(self.thread.isAlive()):
            try:
                self.thread.join(1)
            except KeyboardInterrupt:
                answer = pywikibot.inputChoice(u"""\
    There are %i items remaining in the queue. Estimated time remaining: %s
    Really exit?"""
                                         % remaining(),
                                     ['yes', 'no'], ['y', 'N'], 'N')
                if answer == 'y':
                    return
开发者ID:nullzero,项目名称:wprobot,代码行数:25,代码来源:lthread.py


示例13: put_page

    def put_page(self, page, new):
        """ Print diffs between orginal and new (text), put new text for page

        """
        pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                         % page.title())
        pywikibot.showDiff(page.get(), new)
        if not self.acceptall:
            choice = pywikibot.inputChoice(u'Do you want to accept ' +
                                           u'these changes?',
                                           ['Yes', 'No', 'All'],
                                           ['y', 'N', 'a'], 'N')
            if choice == 'a':
                self.acceptall = True
            if choice == 'y':
                page.text = new
                page.save(self.msg, async=True)
        if self.acceptall:
            try:
                page.text = new
                page.save(self.msg)
            except pywikibot.EditConflict:
                pywikibot.output(u'Skipping %s because of edit conflict'
                                  % (page.title(),))
            except pywikibot.SpamfilterError as e:
                pywikibot.output(
                    u'Cannot change %s because of blacklist entry %s'
                    % (page.title(), e.url))
            except pywikibot.PageNotSaved as error:
                pywikibot.error(u'putting page: %s' % (error.args,))
            except pywikibot.LockedPage:
                pywikibot.output(u'Skipping %s (locked page)'
                                  % (page.title(),))
            except pywikibot.ServerError as e:
                pywikibot.output(u'Server Error : %s' % e)
开发者ID:fdeco,项目名称:pywikibot-core,代码行数:35,代码来源:reflinks.py


示例14: handleNextLink

    def handleNextLink(self, text, match, context=100):
        """
        Returns a tuple (text, jumpToBeginning).

        text is the unicode string after the current link has been processed.
        jumpToBeginning is a boolean which specifies if the cursor position
        should be reset to 0. This is required after the user has edited the
        article.
        """
        # ignore interwiki links and links to sections of the same page as well
        # as section links
        if not match.group('title') \
           or self.pageToUnlink.site.isInterwikiLink(match.group('title')) \
           or match.group('section'):
            return text, False
        linkedPage = pywikibot.Page(self.pageToUnlink.site,
                                    match.group('title'))
        # Check whether the link found is to the current page itself.
        if linkedPage != self.pageToUnlink:
            # not a self-link
            return text, False
        else:
            # at the beginning of the link, start red color.
            # at the end of the link, reset the color to default
            if self.getOption('always'):
                choice = 'a'
            else:
                pywikibot.output(
                    text[max(0, match.start() - context):match.start()]
                    + '\03{lightred}' + text[match.start():match.end()]
                    + '\03{default}' + text[match.end():match.end() + context])
                choice = pywikibot.inputChoice(
                    u'\nWhat shall be done with this link?\n',
                    ['unlink', 'skip', 'edit', 'more context',
                     'unlink all', 'quit'],
                    ['U', 's', 'e', 'm', 'a', 'q'], 'u')
                pywikibot.output(u'')

                if choice == 's':
                    # skip this link
                    return text, False
                elif choice == 'e':
                    editor = TextEditor()
                    newText = editor.edit(text, jumpIndex=match.start())
                    # if user didn't press Cancel
                    if newText:
                        return newText, True
                    else:
                        return text, True
                elif choice == 'm':
                    # show more context by recursive self-call
                    return self.handleNextLink(text, match,
                                               context=context + 100)
                elif choice == 'a':
                    self.options['always'] = True
                elif choice == 'q':
                    self.quit()
            new = match.group('label') or match.group('title')
            new += match.group('linktrail')
            return text[:match.start()] + new + text[match.end():], False
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:60,代码来源:unlink.py


示例15: save

 def save(self, text, page, comment=None, minorEdit=True,
          botflag=True):
     # only save if something was changed
     if text != page.get():
         # 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())
         # show what was changed
         pywikibot.showDiff(page.get(), text)
         pywikibot.output(u'Comment: %s' % comment)
         if not self.dry:
             choice = pywikibot.inputChoice(
                 u'Do you want to accept these changes?',
                 ['Yes', 'No'], ['y', 'N'], 'N')
             if choice == 'y':
                 try:
                     page.text = text
                     # Save the page
                     page.save(comment=comment or self.comment,
                               minor=minorEdit, botflag=botflag)
                 except pywikibot.LockedPage:
                     pywikibot.output(u"Page %s is locked; skipping."
                                      % page.title(asLink=True))
                 except pywikibot.EditConflict:
                     pywikibot.output(
                         u'Skipping %s because of edit conflict'
                         % (page.title()))
                 except pywikibot.SpamfilterError as error:
                     pywikibot.output(
                         u'Cannot change %s because of spam blacklist entry %s'
                         % (page.title(), error.url))
                 else:
                     return True
     return False
开发者ID:octobertech,项目名称:pywikibot-core,代码行数:35,代码来源:basic.py


示例16: userPut

    def userPut(self, page, oldtext, newtext):
        """
        Print differences, ask user for confirmation,
        and puts the page if needed.

        Option used:
            * 'always'
        """
        if oldtext == newtext:
            pywikibot.output(u'No changes were needed on %s'
                             % page.title(asLink=True))
            return

        pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                         % page.title())
        pywikibot.showDiff(oldtext, newtext)

        choice = 'a'
        if not self.getOption('always'):
            choice = pywikibot.inputChoice(
                u'Do you want to accept these changes?',
                ['Yes', 'No', 'All'],
                ['y', 'N', 'a'],
                'N'
            )
            if choice == 'a':
                # Remember the choice
                self.options['always'] = True

        if choice != 'n':
            page.put(newtext, async=(choice == 'a'))
开发者ID:wpoa,项目名称:wiki-imports,代码行数:31,代码来源:bot.py


示例17: save

    def save(self, page, text):
        if text != page.get():
            # 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.showDiff(page.get(), text)
            if not self.always:
                choice = pywikibot.inputChoice(
                    u'Do you want to accept these changes?',
                    ['Yes', 'No', 'Always yes'], ['y', 'N', 'a'], 'N')
                if choice == 'n':
                    return
                elif choice == 'a':
                    self.always = True

            if self.always:
                try:
                    page.put(text, comment=self.comment)
                except pywikibot.EditConflict:
                    pywikibot.output(u'Skipping %s because of edit conflict'
                                     % (page.title(),))
                except pywikibot.SpamfilterError, e:
                    pywikibot.output(
                        u'Cannot change %s because of blacklist entry %s'
                        % (page.title(), e.url))
                except pywikibot.LockedPage:
                    pywikibot.output(u'Skipping %s (locked page)'
                                     % (page.title(),))
开发者ID:Aaron1011,项目名称:pywikibot-core,代码行数:29,代码来源:isbn.py


示例18: save

    def save(self, page, newText):
        """
        Saves the page to the wiki, if the user accepts the changes made.
        """
        pywikibot.showDiff(page.get(), newText)
        if not self.always:
            choice = pywikibot.inputChoice(
                u'Do you want to accept these changes?',
                ['Yes', 'No', 'Always yes'], ['y', 'N', 'a'], 'Y')
            if choice == 'n':
                return
            elif choice == 'a':
                self.always = True

        if self.always:
            try:
                page.put(newText)
            except pywikibot.EditConflict:
                pywikibot.output(u'Skipping %s because of edit conflict'
                                 % (page.title(),))
            except pywikibot.SpamfilterError, e:
                pywikibot.output(
                    u'Cannot change %s because of blacklist entry %s'
                    % (page.title(), e.url))
            except pywikibot.LockedPage:
                pywikibot.output(u'Skipping %s (locked page)' % (page.title(),))
开发者ID:legoktm,项目名称:pywikipedia-original,代码行数:26,代码来源:noreferences.py


示例19: appendtext

def appendtext(page, apptext, always):
    if page.isRedirectPage():
        page = page.getRedirectTarget()
    if not page.exists():
        if page.isTalkPage():
            text = u''
        else:
            raise pywikibot.NoPage(u"Page '%s' does not exist" % page.title())
    else:
        text = page.text
    # Here you can go editing. If you find you do not
    # want to edit this page, just return
    oldtext = text
    text += apptext
    if text != oldtext:
        pywikibot.showDiff(oldtext, text)
        if not always:
            choice = pywikibot.inputChoice(
                u'Do you want to accept these changes?', ['Yes', 'No', 'All'],
                'yNa', 'N')
            if choice == 'a':
                always = True
        if always or choice == 'y':
            page.text = text
            page.save(i18n.translate(pywikibot.Site(), comment,
                                     fallback=True))
开发者ID:legoktm,项目名称:pywikibot-core,代码行数:26,代码来源:unusedfiles.py


示例20: insert_alphabetically

def insert_alphabetically(page, regex, language_code, new, comment, suffix="\n"):
  """
  Inserts the "new" into the list given in site. Each entry of the list, is matched by
  "regex". This regex must have a group named "code" OR a placeholder named "code" ($code).

  This code is then checked against language_code, and if the current code is after the
  language_code it adds the "new" prior to that. The new entry needs a placeholde named code
  ($code).

  On both "regex" and "new" is string.Template.substitute applied. Any trailing $-signs are
  automatically escaped if not done so.
  """
  if re.search(r"[^$](\$\$)*\$$", regex):
    regex += '$'
  oldtext = page.text
  compiled = re.compile(Template(regex).substitute(code=r'(?P<code>[a-z]{2}(-[a-z]{2})?)', newline=r'(?P<newline>\n)?'), re.M)
  print compiled.pattern
  matches = list(compiled.finditer(oldtext))
  if len(matches) == 0:
    print("No matches found.")
    return False
  else:
    insert_at = 0
    got_to_end = False
    for match in matches:
      if match.group('code') == language_code:
        print("Language is already available")
        return False
      elif match.group('code') > language_code:
        insert_at = match.start()
        break
    else:
      insert_at = match.end()
      got_to_end = True
    try:
      if match.start('newline') < 0:
        suffix = ""
      else:
        suffix = "\n"
    except IndexError:
      pass
    print "here we are {}".format(insert_at)
    print oldtext[insert_at]
    if got_to_end and len(oldtext) > insert_at + len(suffix):
      insert_at += len(suffix)
    if insert_at > 0 and len(oldtext) == insert_at - len(suffix) + 1:
      print "+= {}".format(len(suffix))
      oldtext += suffix
    page.text = oldtext[:insert_at]
    if callable(new):
      page.text += new(language_code, match)
    else:
      page.text += Template(new).substitute(code=language_code) + suffix
    page.text += oldtext[insert_at:]
    print("Changes in {}:".format(page.title()))     
    pywikibot.showDiff(oldtext, page.text)
    if pywikibot.inputChoice("Save changes?", ['Yes', 'No'], ['y', 'n'], 'n') == 'y':
      page.save(comment=comment)
    return True
开发者ID:xZise,项目名称:bobbot,代码行数:59,代码来源:add_language.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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