Search code examples
wikipediapywikibot

Is there a way to use the variable "title of the current page" inside a pywikibot replace command?


I would like my pywikibot to remove

| name = whatever

from a wikipedia infobox if the name is equal to the title of the page using the replace function. Is there an easy way to do that?

The code to use should be something like that:

$ python pwb.py replace -regex " *\| *name *\= "TITLEPAGE" *\n" ""

But I am not sure if this option even exists in pywikibot.


Solution

  • unfortunately there is no straightforward way like this. But you definitively can use it inside code by easily creating your own replace.py script. Afterwards you can use something like:

    $ python pwb.py my_replace.py
    

    The contents of scripts/userscripts/my_replace.py could look like:

    # -*- coding: utf-8  -*-
    
    import pywikibot, re
    
    site = pywikibot.Site()
    page = pywikibot.Page(site, 'Page you want to edit')
    new_text = re.sub(r' *\| *name *\= ' + re.escape(page.title()) + r' *\n', r'', text)
    page.text = new_text
    page.save('remove param with page title')
    

    Or you can use generator to generate a list of pages like:

    # -*- coding: utf-8  -*-
    
    import pywikibot, re
    from pywikibot import pagegenerators
    
    site = pywikibot.Site()
    cat = pywikibot.Category(site,'Category:Pages with title in param')
    gen = pagegenerators.CategorizedPageGenerator(cat)
    
    for page in gen:
        new_text = re.sub(r' *\| *name *\= ' + re.escape(page.title()) + r' *\n', r'', text)
        page.text = new_text
        page.save('remove param with page title')
    

    See https://www.mediawiki.org/wiki/Manual:Pywikibot/Create_your_own_script for more details