用户:Yinweichen/make redirect.py

# -*- coding: utf-8 -*-
# Winston Yin 2014-12-20
# 檢查不同譯名的條目名是否存在,如果存在則建立重定向。

import pywikibot

# source: page to be created
# targets: list of alternate page names
# simplified: simplified chinese of source
def make_redirect(source, targets, simplified):
    global site
    page = pywikibot.Page(site, unicode(source, 'utf_8'))
    exists = page.exists()
    # Simplified version needs no redirecting
    if not exists:
        if pywikibot.Page(site, unicode(simplified, 'utf_8')).exists():
            exists = True
            source = simplified
            page = pywikibot.Page(site, unicode(source, 'utf_8'))
    # Source page exists?
    if exists:
        isredirect = page.isRedirectPage()
        if isredirect:
            target_title = page.getRedirectTarget().title().encode('utf_8')
            print(source + ' exists and redirects to ' + target_title + '.')
        else:
            print(source + ' is the main article.')
    else:
        target = ''
        # Check if pages with alternate names exist
        for t in targets:
            tpage = pywikibot.Page(site, unicode(t, 'utf_8'))
            if tpage.exists():
                target = t
                break
        if target != '':
            if tpage.isRedirectPage():
                target_of_target = tpage.getRedirectTarget().title().encode('utf_8') # Get to the root of redirect
            else:
                target_of_target = target
            print(source + ' does not exist. Redirecting to ' + target_of_target + '.')
            outtext = '#redirect[[' + target_of_target + ']]'
            page.text = unicode(outtext, 'utf_8')
            page.save()
        else:
            print('No corresponding page for ' + source + ' exists.')

site = pywikibot.Site('zh', 'wikipedia')
for i in range(1, 433):
    source = '開普勒' + str(i) + 'd'
    targets = ['克卜勒' + str(i) + 'd']
    simplified = '开普勒' + str(i) + 'd'
    make_redirect(source, targets, simplified)