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


Python pywikibot.input_yn函数代码示例

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


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

示例1: useHashGenerator

 def useHashGenerator(self):
     """Use hash generator."""
     # https://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 = ('https://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[s]?://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(color_format(
                 '\n\n>>> {lightpurple}{0}{default} <<<',
                 image_local))
             pywikibot.output(u'Local: %s\nCommons: %s\n'
                              % (url_local, url_commons))
             webbrowser.open(url_local, 0, 1)
             webbrowser.open(url_commons, 0, 1)
             if image_local.split('Image:')[1] == image_commons:
                 choice = pywikibot.input_yn(
                     u'The local and the commons images have the same name, '
                     'continue?', default=False, automatic_quit=False)
             else:
                 choice = pywikibot.input_yn(
                     u'Are the two images equal?',
                     default=False, automatic_quit=False)
             if choice:
                 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:AbdealiJK,项目名称:pywikibot-core,代码行数:59,代码来源:nowcommons.py

示例2: create_user_config

def create_user_config():
    """Create a user-config.py in base_dir."""
    _fnc = os.path.join(base_dir, "user-config.py")
    if not file_exists(_fnc):
        main_family, main_lang, main_username = get_site_and_lang()

        usernames = [(main_family, main_lang, main_username)]
        while pywikibot.input_yn("Do you want to add any other projects?",
                                 default=False, automatic_quit=False):
            usernames += [get_site_and_lang(main_family, main_lang,
                                            main_username)]

        usernames = '\n'.join(
            u"usernames['{0}']['{1}'] = u'{2}'".format(*username)
            for username in usernames)

        extended = pywikibot.input_yn("Would you like the extended version of "
                                      "user-config.py, with explanations "
                                      "included?", automatic_quit=False)

        if extended:
            # config2.py will be in the pywikibot/ directory relative to this
            # script (generate_user_files)
            install = os.path.dirname(os.path.abspath(__file__))
            with codecs.open(os.path.join(install, "pywikibot", "config2.py"),
                             "r", "utf-8") as config_f:
                config = config_f.read()

            res = re.findall("^(############## (?:"
                             "LOGFILE|"
                             "INTERWIKI|"
                             "SOLVE_DISAMBIGUATION|"
                             "IMAGE RELATED|"
                             "TABLE CONVERSION BOT|"
                             "WEBLINK CHECKER|"
                             "DATABASE|"
                             "SEARCH ENGINE|"
                             "COPYRIGHT|"
                             "FURTHER"
                             ") SETTINGS .*?)^(?=#####|# =====)",
                             config, re.MULTILINE | re.DOTALL)
            config_text = '\n'.join(res)
            config_content = EXTENDED_CONFIG
        else:
            config_content = SMALL_CONFIG

        with codecs.open(_fnc, "w", "utf-8") as f:
            f.write(config_content.format(**locals()))
        pywikibot.output(u"'%s' written." % _fnc)
开发者ID:skamithi,项目名称:pywikibot-core,代码行数:49,代码来源:generate_user_files.py

示例3: main

def main(give_url, image_url, desc):
    """Run the bot."""
    url = give_url
    image_url = ''
    if url == '':
        if image_url:
            url = pywikibot.input(u"What URL range should I check "
                                  u"(use $ for the part that is changeable)")
        else:
            url = pywikibot.input(u"From what URL should I get the images?")

    if image_url:
        minimum = 1
        maximum = 99
        answer = pywikibot.input(
            u"What is the first number to check (default: 1)")
        if answer:
            minimum = int(answer)
        answer = pywikibot.input(
            u"What is the last number to check (default: 99)")
        if answer:
            maximum = int(answer)

    if not desc:
        basicdesc = pywikibot.input(
            u"What text should be added at the end of "
            u"the description of each image from this url?")
    else:
        basicdesc = desc

    if image_url:
        ilinks = []
        i = minimum
        while i <= maximum:
            ilinks += [url.replace("$", str(i))]
            i += 1
    else:
        ilinks = get_imagelinks(url)

    for image in ilinks:
        if pywikibot.input_yn('Include image %s?' % image, default=False,
                              automatic_quit=False):
            desc = pywikibot.input(u"Give the description of this image:")
            categories = []
            while True:
                cat = pywikibot.input(u"Specify a category (or press enter to "
                                      u"end adding categories)")
                if not cat.strip():
                    break
                if ":" in cat:
                    categories.append(u"[[%s]]" % cat)
                else:
                    categories.append(u"[[%s:%s]]"
                                      % (mysite.namespace(14), cat))
            desc += "\r\n\r\n" + basicdesc + "\r\n\r\n" + \
                    "\r\n".join(categories)
            uploadBot = UploadRobot(image, description=desc)
            uploadBot.run()
        elif answer == 's':
            break
开发者ID:Darkdadaah,项目名称:pywikibot-core,代码行数:60,代码来源:imageharvest.py

示例4: get_dest

 def get_dest(self):
     self.dest = u'%s-core.%s' % tuple(self.source.rsplit(u'.', 1))
     if not self.warnonly and not pywikibot.input_yn(
             u'Destination file is %s.' % self.dest,
             default=True, automatic_quit=False):
         pywikibot.output('Quitting...')
         exit()
开发者ID:happy5214,项目名称:pywikibot-core,代码行数:7,代码来源:compat2core.py

示例5: save

 def save(self, text, page, comment=None, minorEdit=True,
          botflag=True):
     """ Update the given page with new text. """
     # 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:
             if pywikibot.input_yn(
                     u'Do you want to accept these changes?',
                     default=False, automatic_quit=False):
                 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:Exal117,项目名称:pywikibot-core,代码行数:35,代码来源:basic.py

示例6: upload_file

    def upload_file(self, file_url, debug=False):
        """Upload the image at file_url to the target wiki.

        Return the filename that was used to upload the image.
        If the upload fails, ask the user whether to try again or not.
        If the user chooses not to retry, return null.

        """
        filename = self.process_filename(file_url)
        if not filename:
            return None

        site = self.targetSite
        imagepage = pywikibot.FilePage(site, filename)  # normalizes filename
        imagepage.text = self.description

        pywikibot.output("Uploading file to %s via API..." % site)

        try:
            apiIgnoreWarnings = False
            if self.ignoreWarning is True:
                apiIgnoreWarnings = True
            if self.uploadByUrl:
                site.upload(imagepage, source_url=file_url, ignore_warnings=apiIgnoreWarnings)
            else:
                if "://" in file_url:
                    temp = self.read_file_content(file_url)
                else:
                    temp = file_url
                site.upload(
                    imagepage, source_filename=temp, ignore_warnings=apiIgnoreWarnings, chunk_size=self.chunk_size
                )

        except pywikibot.data.api.UploadWarning as warn:
            pywikibot.output("We got a warning message: {0} - {1}".format(warn.code, warn.message))
            if self.abort_on_warn(warn.code):
                answer = False
            elif self.ignore_on_warn(warn.code):
                answer = True
            else:
                answer = pywikibot.input_yn("Do you want to ignore?", default=False, automatic_quit=False)
            if answer:
                self.ignoreWarning = True
                self.keepFilename = True
                return self.upload_file(file_url, debug)
            else:
                pywikibot.output("Upload aborted.")
                return
        except pywikibot.data.api.APIError as error:
            if error.code == "uploaddisabled":
                pywikibot.error("Upload error: Local file uploads are disabled on %s." % site)
            else:
                pywikibot.error("Upload error: ", exc_info=True)
        except Exception:
            pywikibot.error("Upload error: ", exc_info=True)

        else:
            # No warning, upload complete.
            pywikibot.output("Upload of %s successful." % filename)
            return filename  # data['filename']
开发者ID:hasteur,项目名称:pywikibot_scripts,代码行数:60,代码来源:upload.py

示例7: save

 def save(self, text, page, comment, minorEdit=True, botflag=True):
     """Save the text."""
     if text != page.text:
         # Show the title of the page we're working on.
         # Highlight the title in purple.
         pywikibot.output(color_format(
             '\n\n>>> {lightpurple}{0}{default} <<<', page.title()))
         # show what was changed
         pywikibot.showDiff(page.get(), text)
         pywikibot.output(u'Comment: %s' % comment)
         if not self.dry:
             if pywikibot.input_yn(
                     u'Do you want to accept these changes?',
                     default=False, automatic_quit=False):
                 page.text = text
                 try:
                     # Save the page
                     page.save(summary=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 as error:
                     pywikibot.output(
                         u'Cannot change %s because of spam blacklist entry '
                         u'%s' % (page.title(), error.url))
                 else:
                     return True
开发者ID:KaiCode2,项目名称:pywikibot-core,代码行数:32,代码来源:blockreview.py

示例8: main

def main(*args):
    """
    Process command line arguments and generate user-config.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    global base_dir

    # set the config family and mylang values to an invalid state so that
    # the script can detect that the command line arguments -family & -lang
    # were used and and handle_args has updated these config values,
    # and 'force' mode can be activated below.
    (config.family, config.mylang) = ('wikipedia', None)

    pywikibot.output('You can abort at any time by pressing ctrl-c')

    local_args = pywikibot.handle_args(args)
    if local_args:
        pywikibot.output('Unknown arguments: %s' % ' '.join(local_args))
        return False

    if config.mylang is not None:
        force = True
        pywikibot.output(u'Automatically generating user-config.py')
    else:
        force = False
        # Force default site of en.wikipedia
        (config.family, config.mylang) = ('wikipedia', 'en')

    username = config.usernames[config.family].get(config.mylang)
    args = (config.family, config.mylang, username)

    # Only give option for directory change if user-config.py already exists
    # in the directory. This will repeat if user-config.py also exists in
    # the requested directory.
    if not force or config.verbose_output:
        pywikibot.output(u'\nYour default user directory is "%s"' % base_dir)
        while os.path.isfile(os.path.join(base_dir, "user-config.py")):
            pywikibot.output('user-config.py already exists'
                             ' in the target directory.')
            if pywikibot.input_yn('Would you like to change the directory?',
                                  default=True,
                                  automatic_quit=False, force=force):
                new_base = change_base_dir()
                if new_base:
                    base_dir = new_base
            else:
                break

    # user-fixes.py also used to be created here, but has
    # been replaced by an example file.
    if not os.path.isfile(os.path.join(base_dir, "user-config.py")):
        create_user_config(args, force=force)
    else:
        pywikibot.output('user-config.py already exists in the target '
                         'directory "{0}".'.format(base_dir))
开发者ID:hasteur,项目名称:g13bot_tools_new,代码行数:59,代码来源:generate_user_files.py

示例9: treat

    def treat(self, page):
        """It loads the given page, does some changes, and saves it."""
        choice = False
        try:
            # page: title, date, username, comment, loginfo, rcid, token
            username = page["user"]
            # when the feed isnt from the API, it used to contain
            # '(not yet written)' or '(page does not exist)' when it was
            # a redlink
            rcid = page["rcid"]
            title = page["title"]
            if not rcid:
                raise Exception("rcid not present")

            # check whether we have wrapped around to higher rcids
            # which indicates a new RC feed is being processed
            if rcid > self.last_rcid:
                # refresh the whitelist
                self.load_whitelist()
                self.repeat_start_ts = time.time()

            if pywikibot.config.verbose_output or self.getOption("ask"):
                pywikibot.output("User %s has created or modified page %s" % (username, title))

            if self.getOption("autopatroluserns") and (page["ns"] == 2 or page["ns"] == 3):
                # simple rule to whitelist any user editing their own userspace
                if title.partition(":")[2].split("/")[0].startswith(username):
                    if pywikibot.config.verbose_output:
                        pywikibot.output("%s is whitelisted to modify %s" % (username, title))
                    choice = True

            if not choice and username in self.whitelist:
                if self.in_list(self.whitelist[username], title):
                    if pywikibot.config.verbose_output:
                        pywikibot.output("%s is whitelisted to modify %s" % (username, title))
                    choice = True

            if self.getOption("ask"):
                choice = pywikibot.input_yn("Do you want to mark page as patrolled?", automatic_quit=False)

            # Patrol the page
            if choice:
                # list() iterates over patrol() which returns a generator
                list(self.site.patrol(rcid))
                self.patrol_counter = self.patrol_counter + 1
                pywikibot.output("Patrolled %s (rcid %d) by user %s" % (title, rcid, username))
            else:
                if pywikibot.config.verbose_output:
                    pywikibot.output("Skipped")

            if rcid > self.highest_rcid:
                self.highest_rcid = rcid
            self.last_rcid = rcid
            self.rc_item_counter = self.rc_item_counter + 1

        except pywikibot.NoPage:
            pywikibot.output("Page %s does not exist; skipping." % title(asLink=True))
        except pywikibot.IsRedirectPage:
            pywikibot.output("Page %s is a redirect; skipping." % title(asLink=True))
开发者ID:hasteur,项目名称:pywikibot_scripts,代码行数:59,代码来源:patrol.py

示例10: get_dest

 def get_dest(self):
     """Ask for destination script name."""
     self.dest = u'{0!s}-core.{1!s}'.format(*tuple(self.source.rsplit(u'.', 1)))
     if not self.warnonly and not pywikibot.input_yn(
             u'Destination file is {0!s}.'.format(self.dest),
             default=True, automatic_quit=False):
         pywikibot.output('Quitting...')
         exit()
开发者ID:runt18,项目名称:pywikibot-core,代码行数:8,代码来源:compat2core.py

示例11: main

def main(*args):
    """
    Process command line arguments and invoke bot.

    If args is an empty list, sys.argv is used.

    @param args: command line arguments
    @type args: list of unicode
    """
    options = {}

    # Process global args and prepare generator args parser
    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if arg.startswith('-summary:'):
            options['summary'] = arg[len('-summary:'):]
        elif arg == '-always':
            options['always'] = True
        elif arg == '-async':
            options['async'] = True
        elif arg.startswith('-ignore:'):
            ignore_mode = arg[len('-ignore:'):].lower()
            if ignore_mode == 'method':
                options['ignore'] = cosmetic_changes.CANCEL_METHOD
            elif ignore_mode == 'page':
                options['ignore'] = cosmetic_changes.CANCEL_PAGE
            elif ignore_mode == 'match':
                options['ignore'] = cosmetic_changes.CANCEL_MATCH
            else:
                raise ValueError('Unknown ignore mode "{0}"!'.format(ignore_mode))
        else:
            genFactory.handleArg(arg)

    site = pywikibot.Site()

    if not options.get('summary'):
        # Load default summary message.
        options['summary'] = i18n.twtranslate(site,
                                              'cosmetic_changes-standalone')

    gen = genFactory.getCombinedGenerator()
    if gen:
        if options.get('always') or pywikibot.input_yn(
                warning + '\nDo you really want to continue?',
                default=False, automatic_quit=False):
            site.login()
            preloadingGen = pagegenerators.PreloadingGenerator(gen)
            bot = CosmeticChangesBot(preloadingGen, **options)
            bot.run()
        return True
    else:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
开发者ID:valhallasw,项目名称:pywikibot-core,代码行数:55,代码来源:cosmetic_changes.py

示例12: run

    def run(self):
        """Start the robot's action."""
        # regular expression to find the original template.
        # {{vfd}} does the same thing as {{Vfd}}, so both will be found.
        # The old syntax, {{msg:vfd}}, will also be found.
        # The group 'parameters' will either match the parameters, or an
        # empty string if there are none.

        replacements = []
        exceptions = {}
        site = pywikibot.Site()
        for old, new in self.templates.items():
            namespaces = list(site.namespace(10, all=True))
            if not site.nocapitalize:
                pattern = '[' + \
                          re.escape(old[0].upper()) + \
                          re.escape(old[0].lower()) + \
                          ']' + re.escape(old[1:])
            else:
                pattern = re.escape(old)
            pattern = re.sub(r'_|\\ ', r'[_ ]', pattern)
            templateRegex = re.compile(r'\{\{ *(' + ':|'.join(namespaces) +
                                       r':|[mM][sS][gG]:)?' + pattern +
                                       r'(?P<parameters>\s*\|.+?|) *}}',
                                       re.DOTALL)

            if self.getOption('subst') and self.getOption('remove'):
                replacements.append((templateRegex,
                                     '{{subst:%s\g<parameters>}}' % new))
                exceptions['inside-tags'] = ['ref', 'gallery']
            elif self.getOption('subst'):
                replacements.append((templateRegex,
                                     '{{subst:%s\g<parameters>}}' % old))
                exceptions['inside-tags'] = ['ref', 'gallery']
            elif self.getOption('remove'):
                replacements.append((templateRegex, ''))
            else:
                template = pywikibot.Page(site, new, ns=10)
                if not template.exists():
                    pywikibot.warning(u'Template "%s" does not exist.' % new)
                    if not pywikibot.input_yn('Do you want to proceed anyway?',
                                              default=False, automatic_quit=False):
                        continue
                replacements.append((templateRegex,
                                     '{{%s\g<parameters>}}' % new))

        replaceBot = replace.ReplaceRobot(self.generator, replacements,
                                          exceptions, acceptall=self.getOption('always'),
                                          addedCat=self.getOption('addedCat'),
                                          summary=self.getOption('summary'))
        replaceBot.run()
开发者ID:Exal117,项目名称:pywikibot-core,代码行数:51,代码来源:template.py

示例13: treat_page

    def treat_page(self):
        """Suggest redirects by reordering names in titles."""
        if self.current_page.isRedirectPage():
            return

        page_t = self.current_page.title()
        split_title = page_t.split(' (')
        name = split_title[0]
        site = self.current_page.site

        possible_names = []
        if self.getOption('surnames_last'):
            name_parts = name.split(', ')
            if len(name_parts) == 2 and len(name.split(' ')) <= 3:
                possible_names.append(name_parts[1] + ' ' + name_parts[0])
        else:
            words = name.split()
            if len(words) == 2 and name == name.title():
                possible_names.append(words[1] + ', ' + words[0])
            elif len(words) == 3:
                # title may have at most one non-titlecased word
                if len(SequenceMatcher(None, name,
                   name.title()).get_matching_blocks()) <= 3:
                    possible_names.append(words[1] + ' ' +
                                          words[2] + ', ' +
                                          words[0])
                    possible_names.append(words[2] + ', ' +
                                          words[0] + ' ' +
                                          words[1])

        for possible_name in possible_names:
            # append disambiguation inside parenthesis if there is one
            if len(split_title) == 2:
                possible_name += ' (' + split_title[1]

            new_page = pywikibot.Page(site, possible_name)
            if new_page.exists():
                pywikibot.output('%s already exists, skipping...'
                                 % new_page.title(asLink=True))
            else:
                pywikibot.output('%s doesn\'t exist'
                                 % new_page.title(asLink=True))
                choice = pywikibot.input_yn(
                    'Do you want to create a redirect?')
                if choice:
                    comment = i18n.twtranslate(
                        site,
                        'capitalize_redirects-create-redirect',
                        {'to': page_t})
                    new_page.set_redirect_target(self.current_page,
                                                 create=True, summary=comment)
开发者ID:magul,项目名称:pywikibot-core,代码行数:51,代码来源:surnames_redirects.py

示例14: run

    def run(self):
        """Start the robot's action."""
        # regular expression to find the original template.
        # {{vfd}} does the same thing as {{Vfd}}, so both will be found.
        # The old syntax, {{msg:vfd}}, will also be found.
        # The group 'parameters' will either match the parameters, or an
        # empty string if there are none.

        replacements = []
        exceptions = {}
        namespace = self.site.namespaces[10]
        for old, new in self.templates.items():
            if namespace.case == "first-letter":
                pattern = "[" + re.escape(old[0].upper()) + re.escape(old[0].lower()) + "]" + re.escape(old[1:])
            else:
                pattern = re.escape(old)
            pattern = re.sub(r"_|\\ ", r"[_ ]", pattern)
            templateRegex = re.compile(
                r"\{\{ *(" + ":|".join(namespace) + r":|[mM][sS][gG]:)?" + pattern + r"(?P<parameters>\s*\|.+?|) *}}",
                re.DOTALL,
            )

            if self.getOption("subst") and self.getOption("remove"):
                replacements.append((templateRegex, r"{{subst:%s\g<parameters>}}" % new))
                exceptions["inside-tags"] = ["ref", "gallery"]
            elif self.getOption("subst"):
                replacements.append((templateRegex, r"{{subst:%s\g<parameters>}}" % old))
                exceptions["inside-tags"] = ["ref", "gallery"]
            elif self.getOption("remove"):
                replacements.append((templateRegex, ""))
            else:
                template = pywikibot.Page(self.site, new, ns=10)
                if not template.exists():
                    pywikibot.warning('Template "%s" does not exist.' % new)
                    if not pywikibot.input_yn("Do you want to proceed anyway?", default=False, automatic_quit=False):
                        continue
                replacements.append((templateRegex, r"{{%s\g<parameters>}}" % new))

        replaceBot = replace.ReplaceRobot(
            self.generator,
            replacements,
            exceptions,
            acceptall=self.getOption("always"),
            addedCat=self.getOption("addedCat"),
            summary=self.getOption("summary"),
        )
        replaceBot.run()
开发者ID:Nivgov,项目名称:AvodatGemer,代码行数:47,代码来源:template.py

示例15: treat

    def treat(self, page):
        """Re-directing process.

        Check if pages are in the given form Something, State, and
        if so, create a redirect from Something, ST..
        """
        for sn in self.abbrev:
            R = re.compile(r', %s$' % sn)
            if R.search(page.title()):
                pl = pywikibot.Page(self.site, page.title().replace(sn,
                                    self.abbrev[sn]))
                # A bit hacking here - the real work is done in the
                # 'except pywikibot.NoPage' part rather than the 'try'.

                try:
                    pl.get(get_redirect=True)
                    goal = pl.getRedirectTarget().title()
                    if pywikibot.Page(self.site, goal).exists():
                        pywikibot.output(
                            u"Not creating %s - redirect already exists."
                            % goal)
                    else:
                        pywikibot.warning(
                            u"%s already exists but redirects elsewhere!"
                            % goal)
                except pywikibot.IsNotRedirectPage:
                    pywikibot.warning(
                        u"Page %s already exists and is not a redirect "
                        u"Please check page!"
                        % pl.title())
                except pywikibot.NoPage:
                    if page.isRedirectPage():
                        p2 = page.getRedirectTarget()
                        pywikibot.output(
                            u'Note: goal page is redirect.\nCreating redirect '
                            u'to "%s" to avoid double redirect.' % p2.title())
                    else:
                        p2 = page
                    if self.force or pywikibot.input_yn('Create redirect {0}?'
                                                        .format(pl.title())):
                        pl.set_redirect_target(
                            p2, create=True,
                            summary=i18n.twtranslate(
                                self.site, 'states_redirect-comment'))
开发者ID:magul,项目名称:pywikibot-core,代码行数:44,代码来源:states_redirect.py


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