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

Python i18n.input函数代码示例

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

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



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

示例1: main

def main():
    #page generator
    gen = None
    # This temporary array is used to read the page title if one single
    # page to work on is specified by the arguments.
    pageTitle = []
    # Which namespaces should be processed?
    # default to [] which means all namespaces will be processed
    namespaces = []
    # Never ask before changing a page
    always = False
    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory()

    for arg in pywikibot.handleArgs():
        if arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
            gen = XmlDumpNoReferencesPageGenerator(xmlFilename)
        elif arg.startswith('-namespace:'):
            try:
                namespaces.append(int(arg[11:]))
            except ValueError:
                namespaces.append(arg[11:])
        elif arg == '-always':
            always = True
        else:
            if not genFactory.handleArg(arg):
                pageTitle.append(arg)

    if pageTitle:
        page = pywikibot.Page(pywikibot.getSite(), ' '.join(pageTitle))
        gen = iter([page])
    if not gen:
        gen = genFactory.getCombinedGenerator()
    if not gen:
        site = pywikibot.getSite()
        try:
            cat = maintenance_category[site.family.name][site.lang]
        except:
            pass
        else:
            import catlib
            if not namespaces:
                namespaces = [0]
            cat = catlib.Category(site, "%s:%s" % (site.category_namespace(),
                                                   cat))
            gen = pagegenerators.CategorizedPageGenerator(cat)
    if not gen:
        pywikibot.showHelp('noreferences')
    else:
        if namespaces:
            gen =  pagegenerators.NamespaceFilterPageGenerator(gen, namespaces)
        preloadingGen = pagegenerators.PreloadingGenerator(gen)
        bot = NoReferencesBot(preloadingGen, always)
        bot.run()
开发者ID:valhallasw,项目名称:pwb-test-alpha,代码行数:60,代码来源:noreferences.py


示例2: getCategoryGen

    def getCategoryGen(self, arg, length, recurse=False):
        site = pywikibot.getSite()
        if len(arg) == length:
            categoryname = i18n.input("pywikibot-enter-category-name")
        else:
            categoryname = arg[length + 1 :]
        categoryname = categoryname.replace("#", "|")
        ind = categoryname.find("|")
        startfrom = None
        if ind > 0:
            startfrom = categoryname[ind + 1 :]
            categoryname = categoryname[:ind]

        cat = catlib.Category(site, "%s:%s" % (site.namespace(14), categoryname))
        return CategorizedPageGenerator(cat, start=startfrom, recurse=recurse)
开发者ID:hroest,项目名称:pywikibot-compat,代码行数:15,代码来源:pagegenerators.py


示例3: 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('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
            genFactory.gens.append(XmlDumpNoReferencesPageGenerator(xmlFilename))
        elif arg == '-always':
            options['always'] = True
        elif arg == '-quiet':
            options['verbose'] = False
        else:
            genFactory.handleArg(arg)

    gen = genFactory.getCombinedGenerator()
    if not gen:
        site = pywikibot.Site()
        try:
            cat = site.expand_text(
                site.mediawiki_message(maintenance_category))
        except:
            pass
        else:
            cat = pywikibot.Category(site, "%s:%s" % (
                site.category_namespace(), cat))
            gen = cat.articles(namespaces=genFactory.namespaces or [0])
    if gen:
        bot = NoReferencesBot(gen, **options)
        bot.run()
        return True
    else:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
开发者ID:happy5214,项目名称:pywikibot-core,代码行数:48,代码来源:noreferences.py


示例4: setSubCategoriesGen

    def setSubCategoriesGen(self, arg, length, recurse=False, content=False):
        if len(arg) == length:
            categoryname = i18n.input('pywikibot-enter-category-name')
        else:
            categoryname = arg[length + 1:]

        ind = categoryname.find('|')
        if ind > 0:
            startfrom = categoryname[ind + 1:]
            categoryname = categoryname[:ind]
        else:
            startfrom = None

        cat = pywikibot.Category(pywikibot.Link(categoryname,
                                                defaultNamespace=14))
        return SubCategoriesPageGenerator(cat,
               start=startfrom, recurse=recurse, content=content)
开发者ID:pywikibot,项目名称:core-migration-example,代码行数:17,代码来源:pagegenerators.py


示例5: setSubCategoriesGen

    def setSubCategoriesGen(self, arg, length, recurse=False):
        site = pywikibot.getSite()
        if len(arg) == length:
            categoryname = i18n.input('pywikibot-enter-category-name')
        else:
            categoryname = arg[length + 1:]

        ind = categoryname.find('|')
        if ind > 0:
            startfrom = categoryname[ind + 1:]
            categoryname = categoryname[:ind]
        else:
            startfrom = None

        cat = catlib.Category(site,
                              "%s:%s" % (site.namespace(14), categoryname))
        return SubCategoriesPageGenerator(cat, start=startfrom, recurse=recurse)
开发者ID:Rodehi,项目名称:GFROS,代码行数:17,代码来源:pagegenerators.py


示例6: getCategoryGen

    def getCategoryGen(self, arg, length, recurse=False, content=False):
        if len(arg) == length:
            categoryname = i18n.input('pywikibot-enter-category-name')
        else:
            categoryname = arg[length + 1:]
        categoryname = categoryname.replace('#', '|')
        ind = categoryname.find('|')
        startfrom = None
        if ind > 0:
            startfrom = categoryname[ind + 1:]
            categoryname = categoryname[:ind]

        cat = pywikibot.Category(pywikibot.Link(categoryname,
                                                defaultNamespace=14))
        # Link constructor automatically prepends localized namespace
        # if not included in user's input
        return CategorizedPageGenerator(cat,
               start=startfrom, recurse=recurse, content=content)
开发者ID:pywikibot,项目名称:core-migration-example,代码行数:18,代码来源:pagegenerators.py


示例7: main

def main():
    options = {}

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

    for arg in local_args:
        if arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
            genFactory.gens.append(XmlDumpNoReferencesPageGenerator(xmlFilename))
        elif arg == '-always':
            options['always'] = True
        elif arg == '-quiet':
            options['verbose'] = False
        else:
            genFactory.handleArg(arg)

    gen = genFactory.getCombinedGenerator()
    if not gen:
        site = pywikibot.Site()
        try:
            cat = site.expand_text(
                site.mediawiki_message(maintenance_category))
        except:
            pass
        else:
            cat = pywikibot.Category(site, "%s:%s" % (
                site.category_namespace(), cat))
            gen = cat.articles(namespaces=genFactory.namespaces or [0])
    if gen:
        bot = NoReferencesBot(gen, **options)
        bot.run()
    else:
        pywikibot.showHelp()
开发者ID:anrao91,项目名称:pywikibot-core,代码行数:38,代码来源:noreferences.py


示例8: 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
    """
    add_cat = None
    gen = None
    # summary message
    edit_summary = ""
    # Array which will collect commandline parameters.
    # First element is original text, second element is replacement text.
    commandline_replacements = []
    # A list of 2-tuples of original text and replacement text.
    replacements = []
    # Don't edit pages which contain certain texts.
    exceptions = {
        "title": [],
        "text-contains": [],
        "inside": [],
        "inside-tags": [],
        "require-title": [],  # using a seperate requirements dict needs some
    }  # major refactoring of code.

    # Should the elements of 'replacements' and 'exceptions' be interpreted
    # as regular expressions?
    regex = False
    # Predefined fixes from dictionary 'fixes' (see above).
    fixes_set = []
    # the dump's path, either absolute or relative, which will be used
    # if -xml flag is present
    xmlFilename = None
    useSql = False
    # will become True when the user presses a ('yes to all') or uses the
    # -always flag.
    acceptall = False
    # Will become True if the user inputs the commandline parameter -nocase
    caseInsensitive = False
    # Will become True if the user inputs the commandline parameter -dotall
    dotall = False
    # Will become True if the user inputs the commandline parameter -multiline
    multiline = False
    # Do all hits when they overlap
    allowoverlap = False
    # Do not recurse replacement
    recursive = False
    # Between a regex and another (using -fix) sleep some time (not to waste
    # too much CPU
    sleep = None
    # Request manual replacements even if replacements are already defined
    manual_input = False
    # Replacements loaded from a file
    replacement_file = None
    replacement_file_arg_misplaced = False

    # Read commandline parameters.

    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if genFactory.handleArg(arg):
            continue
        if arg == "-regex":
            regex = True
        elif arg.startswith("-xmlstart"):
            if len(arg) == 9:
                xmlStart = pywikibot.input("Please enter the dumped article to start with:")
            else:
                xmlStart = arg[10:]
        elif arg.startswith("-xml"):
            if len(arg) == 4:
                xmlFilename = i18n.input("pywikibot-enter-xml-filename")
            else:
                xmlFilename = arg[5:]
        elif arg == "-sql":
            useSql = True
        elif arg.startswith("-excepttitle:"):
            exceptions["title"].append(arg[13:])
        elif arg.startswith("-requiretitle:"):
            exceptions["require-title"].append(arg[14:])
        elif arg.startswith("-excepttext:"):
            exceptions["text-contains"].append(arg[12:])
        elif arg.startswith("-exceptinside:"):
            exceptions["inside"].append(arg[14:])
        elif arg.startswith("-exceptinsidetag:"):
            exceptions["inside-tags"].append(arg[17:])
        elif arg.startswith("-fix:"):
            fixes_set += [arg[5:]]
        elif arg.startswith("-sleep:"):
            sleep = float(arg[7:])
        elif arg == "-always":
            acceptall = True
        elif arg == "-recursive":
            recursive = True
        elif arg == "-nocase":
            caseInsensitive = True
#.........这里部分代码省略.........
开发者ID:PersianWikipedia,项目名称:pywikibot-core,代码行数:101,代码来源:replace.py


示例9: test_pagegen_i18n_input

 def test_pagegen_i18n_input(self):
     """Test i18n.input falls back with missing message package."""
     rv = i18n.input('pywikibot-enter-category-name',
                     fallback_prompt='dummy output')
     self.assertEqual(rv, 'dummy input')
     self.assertIn('dummy output: ', self.output_text)
开发者ID:edgarskos,项目名称:pywikibot_scripts,代码行数:6,代码来源:i18n_tests.py


示例10: 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 = {}
    # what the bot should do (either resolve double redirs, or delete broken
    # redirs)
    action = None
    # where the bot should get his infos from (either None to load the
    # maintenance special page from the live wiki, or the filename of a
    # local XML dump file)
    xmlFilename = None
    # Which namespace should be processed when using a XML dump
    # default to -1 which means all namespaces will be processed
    namespaces = []
    # at which redirect shall we start searching double redirects again
    # (only with dump); default to -1 which means all redirects are checked
    offset = -1
    moved_pages = False
    fullscan = False
    start = ''
    until = ''
    number = None
    step = None
    pagename = None

    for arg in pywikibot.handle_args(args):
        if arg == 'double' or arg == 'do':
            action = 'double'
        elif arg == 'broken' or arg == 'br':
            action = 'broken'
        elif arg == 'both':
            action = 'both'
        elif arg == '-fullscan':
            fullscan = True
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
        elif arg.startswith('-moves'):
            moved_pages = True
        elif arg.startswith('-namespace:'):
            ns = arg[11:]
            if ns == '':
                # "-namespace:" does NOT yield -namespace:0 further down the road!
                ns = i18n.input('pywikibot-enter-namespace-number')
            # TODO: at least for some generators enter a namespace by its name
            # or number
            if ns == '':
                ns = '0'
            try:
                ns = int(ns)
            except ValueError:
                # -namespace:all Process all namespaces.
                # Only works with the API read interface.
                pass
            if ns not in namespaces:
                namespaces.append(ns)
        elif arg.startswith('-offset:'):
            offset = int(arg[8:])
        elif arg.startswith('-start:'):
            start = arg[7:]
        elif arg.startswith('-until:'):
            until = arg[7:]
        elif arg.startswith('-total:'):
            number = int(arg[7:])
        elif arg.startswith('-step:'):
            step = int(arg[6:])
        elif arg.startswith('-page:'):
            pagename = arg[6:]
        elif arg == '-always':
            options['always'] = True
        elif arg == '-delete':
            options['delete'] = True
        else:
            pywikibot.output(u'Unknown argument: %s' % arg)

    if (
        not action or
        xmlFilename and moved_pages or
        fullscan and xmlFilename
    ):
        problems = []
        if xmlFilename and moved_pages:
            problems += ['Either use a XML file or the moved pages from the API']
        if xmlFilename and fullscan:
            problems += ['Either use a XML file or do a full scan using the API']
        pywikibot.bot.suggest_help(additional_text='\n'.join(problems),
                                   missing_action=not action)
    else:
        pywikibot.Site().login()
        gen = RedirectGenerator(xmlFilename, namespaces, offset, moved_pages,
                                fullscan, start, until, number, step, pagename)
        bot = RedirectRobot(action, gen, number=number, **options)
#.........这里部分代码省略.........
开发者ID:happy5214,项目名称:pywikibot-core,代码行数:101,代码来源:redirect.py


示例11: main

def main(*args):
    pywikibot.output('Starting hewiki-replacebot')
    editSummary=replaceConfig.defaultSummary
    xmlFilename=None
    for arg in pywikibot.handleArgs(*args):
        if arg.startswith('-summary:'):
            editSummary = arg[9:]
        elif arg.startswith('-xmlstart'):
            if len(arg) == 9:
                xmlStart = pywikibot.input(
                    u'Please enter the dumped article to start with:')
            else:
                xmlStart = arg[10:]
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]

    if xmlFilename==None:
        pywikibot.output('no xml dump specified. please fill -xml and the xml file to be used')
        return
    replaceDict,exceptReplace=fillReplementsDict()
    try:
        xmlStart
    except NameError:
        xmlStart = None

    safeTemplates=replaceConfig.safeTemplates
    #add external links templates
    genFactory = pagegenerators.GeneratorFactory()
    for safeCategory in replaceConfig.safeTemplatesCategories:
        citeTemplates=genFactory.getCategoryGen(safeCategory,-1, True)
        citeTemplates=[page.title(withNamespace=False) for page in citeTemplates]
        safeTemplates+=citeTemplates
        
    fileUsageRgx=re.compile(replaceConfig.fileUsageRgx,re.I)
    yiRgx=re.compile('\[\[yi:.*?\]\]')
    safeTemplatesRgx=re.compile(u'\{\{('+string.join(safeTemplates,u'|')+').*?\}\}',re.I)
    exceptions = {
        'title':         [],
        'text-contains': [re.compile(replaceConfig.redirectRgx,re.I)],
        'inside':        [fileUsageRgx,safeTemplatesRgx, re.compile(u'('+string.join(exceptReplace,u'|')+')'),yiRgx],
        'inside-tags':   ['nowiki','math','comment','pre','source','hyperlink','gallery'],
        'require-title': [],
    }
    gen = XmlDumpReplacePageGeneratorHe(replaceDict, xmlFilename, xmlStart, exceptions)
    genFactory.namespaces=replaceConfig.namespaces
    #For debugging pupose, uncomment it to work on specific page
    #pages = [pywikibot.Page(pywikibot.getSite(), PageTitle)
    #                 for PageTitle in [u'PAGENAME']]
    #gen = iter(pages)
    #end of specific page
    maxquerysize=60
    gen = genFactory.getCombinedGenerator(gen)
    preloadingGen = pagegenerators.PreloadingGenerator(gen,pageNumber=maxquerysize)
    gen=pagegenerators.EdittimeFilterPageGenerator(preloadingGen, endtime=datetime.datetime.utcnow()-datetime.timedelta(days=1))
    pywikibot.output('starting replace')
    bot=ReplaceRobotHe(gen,replaceDict,exceptions,editSummary)
    bot.run()
    pywikibot.output('finished all replacements')
开发者ID:dekeleini,项目名称:hewiki-ReplaceBot,代码行数:61,代码来源:hewikiReplacebot.py


示例12: 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
    """
    gen = None
    xmlFilename = None
    HTTPignore = []
    day = 7

    if isinstance(memento_client, ImportError):
        warn('memento_client not imported: %s' % memento_client, ImportWarning)

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

    for arg in local_args:
        if arg == '-talk':
            config.report_dead_links_on_talk = True
        elif arg == '-notalk':
            config.report_dead_links_on_talk = False
        elif arg == '-repeat':
            gen = RepeatPageGenerator()
        elif arg.startswith('-ignore:'):
            HTTPignore.append(int(arg[8:]))
        elif arg.startswith('-day:'):
            day = int(arg[5:])
        elif arg.startswith('-xmlstart'):
            if len(arg) == 9:
                xmlStart = pywikibot.input(
                    u'Please enter the dumped article to start with:')
            else:
                xmlStart = arg[10:]
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
        else:
            genFactory.handleArg(arg)

    if xmlFilename:
        try:
            xmlStart
        except NameError:
            xmlStart = None
        gen = XmlDumpPageGenerator(xmlFilename, xmlStart, genFactory.namespaces)

    if not gen:
        gen = genFactory.getCombinedGenerator()
    if gen:
        # fetch at least 240 pages simultaneously from the wiki, but more if
        # a high thread number is set.
        pageNumber = max(240, config.max_external_links * 2)
        gen = pagegenerators.PreloadingGenerator(gen, step=pageNumber)
        gen = pagegenerators.RedirectFilterPageGenerator(gen)
        bot = WeblinkCheckerRobot(gen, HTTPignore, day)
        try:
            bot.run()
        finally:
            waitTime = 0
            # Don't wait longer than 30 seconds for threads to finish.
            while countLinkCheckThreads() > 0 and waitTime < 30:
                try:
                    pywikibot.output(u"Waiting for remaining %i threads to "
                                     u"finish, please wait..."
                                     % countLinkCheckThreads())
                    # wait 1 second
                    time.sleep(1)
                    waitTime += 1
                except KeyboardInterrupt:
                    pywikibot.output(u'Interrupted.')
                    break
            if countLinkCheckThreads() > 0:
                pywikibot.output(u'Remaining %i threads will be killed.'
                                 % countLinkCheckThreads())
                # Threads will die automatically because they are daemonic.
            if bot.history.reportThread:
                bot.history.reportThread.shutdown()
                # wait until the report thread is shut down; the user can
                # interrupt it by pressing CTRL-C.
                try:
                    while bot.history.reportThread.isAlive():
                        time.sleep(0.1)
                except KeyboardInterrupt:
                    pywikibot.output(u'Report thread interrupted.')
                    bot.history.reportThread.kill()
            pywikibot.output(u'Saving history...')
            bot.history.save()
        return True
    else:
        pywikibot.bot.suggest_help(missing_generator=True)
        return False
开发者ID:metakgp,项目名称:batman,代码行数:98,代码来源:weblinkchecker.py


示例13: main

def main(*args):
    # read command line parameters
    # what the bot should do (either resolve double redirs, or delete broken
    # redirs)
    action = None
    # where the bot should get his infos from (either None to load the
    # maintenance special page from the live wiki, or the filename of a
    # local XML dump file)
    xmlFilename = None
    # Which namespace should be processed when using a XML dump
    # default to -1 which means all namespaces will be processed
    namespaces = []
    # at which redirect shall we start searching double redirects again
    # (only with dump); default to -1 which means all redirects are checked
    offset = -1
    moved_pages = False
    fullscan = False
    start = ''
    until = ''
    number = None
    step = None
    always = False
    delete = False
    for arg in pywikibot.handleArgs(*args):
        if arg == 'double' or arg == 'do':
            action = 'double'
        elif arg == 'broken' or arg == 'br':
            action = 'broken'
        elif arg == 'both':
            action = 'both'
        elif arg == '-fullscan':
            fullscan = True
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
        elif arg.startswith('-moves'):
            moved_pages = True
        elif arg.startswith('-namespace:'):
            ns = arg[11:]
            if ns == '':
                # "-namespace:" does NOT yield -namespace:0 further down the road!
                ns = i18n.input('pywikibot-enter-namespace-number')
            # TODO! at least for some generators enter a namespace by its name
            # or number
            if ns == '':
                ns = '0'
            try:
                ns = int(ns)
            except ValueError:
                # -namespace:all Process all namespaces.
                # Only works with the API read interface.
                pass
            if ns not in namespaces:
                namespaces.append(ns)
        elif arg.startswith('-offset:'):
            offset = int(arg[8:])
        elif arg.startswith('-start:'):
            start = arg[7:]
        elif arg.startswith('-until:'):
            until = arg[7:]
        elif arg.startswith('-total:'):
            number = int(arg[7:])
        elif arg.startswith('-step:'):
            step = int(arg[6:])
        elif arg == '-always':
            always = True
        elif arg == '-delete':
            delete = True
        else:
            pywikibot.output(u'Unknown argument: %s' % arg)

    if (
        not action or
        xmlFilename and moved_pages or
        fullscan and xmlFilename
    ):
        pywikibot.showHelp()
    else:
        gen = RedirectGenerator(xmlFilename, namespaces, offset, moved_pages,
                                fullscan, start, until, number, step)
        bot = RedirectRobot(action, gen, always, number, delete)
        bot.run()
开发者ID:legoktm,项目名称:pywikibot-core,代码行数:84,代码来源:redirect.py


示例14: 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
    """
    add_cat = None
    gen = None
    # summary message
    edit_summary = u""
    # Array which will collect commandline parameters.
    # First element is original text, second element is replacement text.
    commandline_replacements = []
    # A list of 2-tuples of original text and replacement text.
    replacements = []
    # Don't edit pages which contain certain texts.
    exceptions = {
        'title':         [],
        'text-contains': [],
        'inside':        [],
        'inside-tags':   [],
        'require-title': [],  # using a seperate requirements dict needs some
    }                        # major refactoring of code.

    # Should the elements of 'replacements' and 'exceptions' be interpreted
    # as regular expressions?
    regex = False
    # Predefined fixes from dictionary 'fixes' (see above).
    fixes_set = []
    # the dump's path, either absolute or relative, which will be used
    # if -xml flag is present
    xmlFilename = None
    useSql = False
    # will become True when the user presses a ('yes to all') or uses the
    # -always flag.
    acceptall = False
    # Will become True if the user inputs the commandline parameter -nocase
    caseInsensitive = False
    # Will become True if the user inputs the commandline parameter -dotall
    dotall = False
    # Will become True if the user inputs the commandline parameter -multiline
    multiline = False
    # Do all hits when they overlap
    allowoverlap = False
    # Do not recurse replacement
    recursive = False
    # Between a regex and another (using -fix) sleep some time (not to waste
    # too much CPU
    sleep = None

    # Read commandline parameters.

    local_args = pywikibot.handle_args(args)
    genFactory = pagegenerators.GeneratorFactory()

    for arg in local_args:
        if genFactory.handleArg(arg):
            continue
        if arg == '-regex':
            regex = True
        elif arg.startswith('-xmlstart'):
            if len(arg) == 9:
                xmlStart = pywikibot.input(
                    u'Please enter the dumped article to start with:')
            else:
                xmlStart = arg[10:]
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
        elif arg == '-sql':
            useSql = True
        elif arg.startswith('-excepttitle:'):
            exceptions['title'].append(arg[13:])
        elif arg.startswith('-requiretitle:'):
            exceptions['require-title'].append(arg[14:])
        elif arg.startswith('-excepttext:'):
            exceptions['text-contains'].append(arg[12:])
        elif arg.startswith('-exceptinside:'):
            exceptions['inside'].append(arg[14:])
        elif arg.startswith('-exceptinsidetag:'):
            exceptions['inside-tags'].append(arg[17:])
        elif arg.startswith('-fix:'):
            fixes_set += [arg[5:]]
        elif arg.startswith('-sleep:'):
            sleep = float(arg[7:])
        elif arg == '-always':
            acceptall = True
        elif arg == '-recursive':
            recursive = True
        elif arg == '-nocase':
            caseInsensitive = True
        elif arg == '-dotall':
            dotall = True
        elif arg == '-multiline':
            multiline = True
#.........这里部分代码省略.........
开发者ID:leogregianin,项目名称:pywikibot-core,代码行数:101,代码来源:replace.py


示例15: 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 = {}
    # what the bot should do (either resolve double redirs, or delete broken
    # redirs)
    action = None
    # where the bot should get his infos from (either None to load the
    # maintenance special page from the live wiki, or the filename of a
    # local XML dump file)
    xmlFilename = None
    # Which namespace should be processed when using a XML dump
    # default to -1 which means all namespaces will be processed
    namespaces = []
    # at which redirect shall we start searching double redirects again
    # (only with dump); default to -1 which means all redirects are checked
    offset = -1
    moved_pages = False
    fullscan = False
    start = ''
    until = ''
    number = None
    pagename = None

    for arg in pywikibot.handle_args(args):
        arg, sep, value = arg.partition(':')
        option = arg[1:]
        # bot options
        if arg == 'do':
            action = 'double'
        elif arg == 'br':
            action = 'broken'
        elif arg in ('both', 'broken', 'double'):
            action = arg
        elif option in ('always', 'delete'):
            options[option] = True
        elif option == 'total':
            options['number'] = number = int(value)
        # generator options
        elif option == 'fullscan':
            fullscan = True
        elif option == 'xml':
            xmlFilename = value or i18n.input('pywikibot-enter-xml-filename')
        elif option == 'moves':
            moved_pages = True
        elif option == 'namespace':
            # "-namespace:" does NOT yield -namespace:0 further down the road!
            ns = value or i18n.input('pywikibot-enter-namespace-number')
            # TODO: at least for some generators enter a namespace by its name
            # or number
            if ns == '':
                ns = '0'
            try:
                ns = int(ns)
            except ValueError:
                # -namespace:all Process all namespaces.
                # Only works with the API read interface.
                pass
            if ns not in namespaces:
                namespaces.append(ns)
        elif option == 'offset':
            offset = int(value)
        elif option == 'start':
            start = value
        elif option == 'until':
            until = value
        elif option == 'page':
            pagename = value
        # deprecated or unknown options
        elif option == 'step':
            issue_deprecation_warning('The usage of "{0}"'.format(arg),
                                      2, ArgumentDeprecationWarning)
        else:
            pywikibot.output(u'Unknown argument: {0!s}'.format(arg))

    if not action or xmlFilename and (moved_pages or fullscan):
        problems = []
        if xmlFilename and moved_pages:
            problems += ['Either use a XML file or the moved pages from the API']
        if xmlFilename and fullscan:
            problems += ['Either use a XML file or do a full scan using the API']
        pywikibot.bot.suggest_help(additional_text='\n'.join(problems),
                                   missing_action=not action)
    else:
        pywikibot.Site().login()
        gen = RedirectGenerator(xmlFilename, namespaces, offset, moved_pages,
                                fullscan, start, until, number, pagename)
        bot = RedirectRobot(action, gen, **options)
        bot.run()
开发者ID:runt18,项目名称:pywikibot-core,代码行数:95,代码来源:redirect.py


示例16: run

 def run(self):
     """
     Starts the robot.
     """
     # Run the generator which will yield Pages which might need to be
     # changed.
     for page in self.generator:
         if self.isTitleExcepted(page.title()):
             pywikibot.output(
                 u'Skipping %s because the title is on the exceptions list.'
                 % page.title(asLink=True))
             continue
         try:
             # Load the page's text from the wiki
             original_text = page.get(get_redirect=True)
             if not (self.articles or page.canBeEdited()):
                 pywikibot.output(u"You can't edit page %s"
                                  % page.title(asLink=True))
                 continue
         except pywikibot.NoPage:
             pywikibot.output(u'Page %s not found' % page.title(asLink=True))
             continue
         new_text = original_text
         while True:
             if self.isTextExcepted(new_text):
                 pywikibot.output(
 u'Skipping %s because it contains text that is on the exceptions list.'
                                  % page.title(asLink=True))
                 break
             new_text = self.doReplacements(new_text)
             if new_text == original_text:
                 pywikibot.output(u'No changes were necessary in %s'
                                  % page.title(asLink=True))
                 break
             if self.recursive:
                 newest_text = self.doReplacements(new_text)
                 while (newest_text!=new_text):
                     new_text = newest_text
                     newest_text = self.doReplacements(new_text)
             if hasattr(self, "addedCat"):
                 cats = page.categories()
                 if self.addedCat not in cats:
                     cats.append(self.addedCat)
                     new_text = pywikibot.replaceCategoryLinks(new_text,
                                                               cats)
             # 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(original_text, new_text)
             if self.acceptall:
                 break
             if self.exctitles:
                 choice = pywikibot.inputChoice(
                         u'Do you want to accept these changes?',
                         ['Yes', 'No', 'no+eXcept', 'Edit',
                          'open in Browser', 'All', 'Quit'],
                         ['y', 'N', 'x', 'e', 'b', 'a', 'q'], 'N')
             else:
                 choice = pywikibot.inputChoice(
                         u'Do you want to accept these changes?',
                         ['Yes', 'No', 'Edit', 'open in Browser', 'All',
                          'Quit'],
                         ['y', 'N', 'e', 'b', 'a', 'q'], 'N')
             if choice == 'e':
                 editor = editarticle.TextEditor()
                 as_edited = editor.edit(original_text)
                 # if user didn't press Cancel
                 if as_edited and as_edited != new_text:
                     new_text = as_edited
                 continue
             if choice == 'b':
                 webbrowser.open("http://%s%s" % (
                     page.site.hostname(),
                     page.site.nice_get_address(page.title())
                 ))
                 i18n.input('pywikibot-enter-finished-browser')
                 try:
                     original_text = page.get(get_redirect=True, force=True)
                 except pywikibot.NoPage:
                     pywikibot.output(u'Page %s has been deleted.'
                                      % page.title())
                     break
                 new_text = original_text
                 continue
             if choice == 'q':
                 self.writeEditCounter()
                 self.writeExceptCounter()
                 return
             if choice == 'a':
                 self.acceptall = True
             if choice == 'x': #May happen only if self.exctitles isn't None
                 self.exctitles.write(
                     u"ur'^%s$',\n" % re.escape(page.title()))
                 self.exctitles.flush()
                 self.exceptcounter += 1
             if choice == 'y':
                 if not self.articles:
                     # Primary behaviour: working on wiki
                     page.put_async(new_text, self.editSummary)
#.........这里部分代码省略.........
开发者ID:tuxnani,项目名称:pyrhmn,代码行数:101,代码来源:replace.py


示例17: main

def main(*args):
    add_cat = None
    gen = None
    # summary message
    summary_commandline = False
    # Array which will collect commandline parameters.
    # First element is original text, second element is replacement text.
    commandline_replacements = []
    # A list of 2-tuples of original text and replacement text.
    replacements = []
    # Don't edit pages which contain certain texts.
    exceptions = {
        'title':         [],
        'text-contains': [],
        'inside':        [],
        'inside-tags':   [],
        'require-title': [], # using a seperate requirements dict needs some
    }                        # major refactoring of code.

    # Should the elements of 'replacements' and 'exceptions' be interpreted
    # as regular expressions?
    regex = False
    # Predefined fixes from dictionary 'fixes' (see above).
    fix = None
    # the dump's path, either absolute or relative, which will be used
    # if -xml flag is present
    xmlFilename = None
    useSql = False
    PageTitles = []
    # will become True when the user presses a ('yes to all') or uses the
    # -always flag.
    acceptall = False
    # Will become True if the user inputs the commandline parameter -nocase
    caseInsensitive = False
    # Will become True if the user inputs the commandline parameter -dotall
    dotall = False
    # Will become True if the user inputs the commandline parameter -multiline
    multiline = False
    # Do all hits when they overlap
    allowoverlap = False
    # Do not recurse replacement
    recursive = False
    # This is the maximum number of pages to load per query
    maxquerysize = 60
    # This factory is responsible for processing command line arguments
    # that are also used by other scripts and that determine on which pages
    # to work on.
    genFactory = pagegenerators.GeneratorFactory()
    # Load default summary message.
    # BUG WARNING: This is probably incompatible with the -lang parameter.
    editSummary = i18n.twtranslate(pywikibot.getSite(), 'replace-replacing',
                                   {'description': u''})
    # Between a regex and another (using -fix) sleep some time (not to waste
    # too much CPU
    sleep = None
    # Do not save the page titles, rather work on wiki
    filename = None # The name of the file to save titles
    titlefile = None # The file object itself
    # If we save, primary behaviour is append rather then new file
    append = True
    # Default: don't write titles to exception file and don't read them.
    excoutfilename = None # The name of the file to save exceptions
    excoutfile = None # The file object itself
    # excinfilename: reserved for later use (reading back exceptions)
    # If we save exceptions, primary behaviour is append
    excappend = True


    # Read commandline parameters.
    for arg in pywikibot.handleArgs(*args):
        if arg == '-regex':
            regex = True
        elif arg.startswith('-xmlstart'):
            if len(arg) == 9:
                xmlStart = pywikibot.input(
                    u'Please enter the dumped article to start with:')
            else:
                xmlStart = arg[10:]
        elif arg.startswith('-xml'):
            if len(arg) == 4:
                xmlFilename = i18n.input('pywikibot-enter-xml-filename')
            else:
                xmlFilename = arg[5:]
        elif arg =='-sql':
            useSql = True
        elif arg.startswith('-page'):
           

鲜花

握手

雷人

路过

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

请发表评论

全部评论

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