Manual:Pywikibot/replace.py

Replace.py is part of the Python Wikipedia Robot framework.

This bot replaces text. It will retrieve information on which pages might need changes either from an XML dump or a text file, or only change a single page. To get some more information, use python replace.py -help

If you have Windows, you may omit "python".

Overview
You may use this script basically in two ways:
 * 1) You write all the parameters into the command line, including the text to be replaced and the replacement. This is useful for simple tasks. For example, will search for word "color" only in articles (ns:0), changes the lower case occurrences to "colour", asks you each time to confirm the replacement, and uses the default edit comment. Be careful, because there are cases where color must not be changed to colour (e.g. in article Cascading Style Sheets); never run such a replacement automatically unless you are at least 100% sure it is always correct! This is almost the simplest form of the command (see below at the minimal parameters).   is equivalent to writing the word color into the search bar and is a fast way of gathering articles, but will not find colored and colors.
 * Should either the old or the new text contain spaces, use quotation marks!
 * Repeated tasks may be stored in a batch file (Windows) or shell script (Linux).
 * 1) You store the main parameters, including old and new text, exceptions and edit comment in a file. Several tasks (called fixes) may be stored in one file and used repeatedly. This file may be either fixes.py which is included in your Pywikipedia distribution, but is subject to change at every update, so you have to save it for yourself, or user-fixes.py that is designed for personal use, but is not included in Pywiki and may be created with generate_user_files.py. This latter one has a slightly different syntax, but has an example. This is much more efficient and flexible but needs some preparation. These two methods may be combined; however, some parameters stored in the fix will overwrite corresponding parameter given in command line.

Once you have chosen between these options, you have another decision:
 * 1) You make simple text replacements like the above one. This is a good way for changing words, templates, categories, section titles or names, but is not flexible. For example, the above command will replace "color", but not colors, colored and Color in upper case. (If you are worried only about the case, you may still type .)
 * 2) You use regular expressions (often mentioned as regexes). These seek patterns and replace them with patterns. There are some examples in fixes.py. For agglutinative and inflecting languages this is the only efficient way of spelling corrections.

Your third decision will be this:
 * 1) You search for pages to be modified in the live wiki. This will result in acceptable speed if you work with templates, categories or the search engine, but is usually very slow for simple iteration of pages, especially in large and medium sized wikis. So  is the least recommended way of usage as it wastes your time and the resources of the server. (However, sometimes it is necessary and unavoidable if your wiki does not have dumps.)
 * 2) You download an XML dump of your wiki from http://dumps.wikimedia.org/ (usually xxwiki-latest-pages-articles.xml.bz2) and use it with  or , while you sleep, have your lunch or write some new articles for Wikipedia. In this case you may use   since no edit in real wiki will be made. Later in a second session you may run the fix again with   with much less dead time.

At least these data should be given for the bot every time:
 * Minimal set of parameters
 * 1) Where and how to search for the pages to be edited?
 * The corresponding parameter may be any of -start, -file, -page, -search, -xml, -cat etc.; see the Source section of the below table.
 * 1) The old text to be replaced and the new one to be substituted.
 * This may be one or more pairs of strings or the name of a fix.
 * 1) It is not mandatory, but usually worth and strongly recommended for beginners to limit the work to the main namespace with -ns:0. Thus you can avoid changing the contributions of users on talk pages or correcting the title of an article on a page where the talk is just about that title. Visible part of templates (but not the code itself!) and file descriptions are also in the scope of readers. It is better not to modify talk pages, user pages and project pages (the "Wikipedia" namespace) in the first time, and it needs special care and community consensus even later. Don't be surprised of angry reactions or your bot being blocked if you omit the namespace parameter.

Files
The bot uses three files in addition to the framework:
 * replace.py : the main module
 * fixes.py : a few predefined "fixes"
 * user-fixes.py</tt> : a file to add ones own fixes. The file is created nearly empty by generate_user_files.py</tt>

Files that may be used for input and/or output:
 * filename.txt</tt> : a file with a list of articles if specified with the parameter "-file", or
 * a file in which the bot will save the list of articles for later use (specified with "-save"/"-savenew")


 * filename.xml</tt> : a local XML dump if used with parameter "-xml"
 * replacelog</tt> : the log with a name that may be specified with parameter "-log"

Local
You can run replace.py with the following parameters (for example, ).

Examples
If you want to change templates from the old syntax, e.g., to the new syntax, e.g., download an XML dump file (page table) from http://download.wikimedia.org, then use this command:

python replace.py -xml -regex "" ""

You can match patterns across more than one line:

python replace.py -regex -start:! "First line\nSecond line" ""

You can insert or append text to a page (note the replacement text has embedded new lines):

python replace.py -regex '(?s)^(.*)$' "\1   > ==new message==    > blah    > "

If you have a dump called foobar.xml and want to fix typos, e.g. Errror -> Error, use this:

python replace.py -xml:foobar.xml "Errror" "Error"

If you have a page called 'John Doe' and want to convert HTML tags to wiki syntax, use: python replace.py -page:John_Doe -fix:HTML

If you run the bot without arguments you will be prompted multiple times for replacements:

python replace.py -file:blah.txt

The script asks the user before modifying an article. It is recommended to double-check the result to be sure that the bot did not introduce errors (especially with misspelled words). It is possible to specify a set of articles with an external text file containing Wiki links :

plane vehicle train car

The bot is then called using something like :

python replace.py [global-arguments] -file:articles_list.txt "errror" "error"

Rather than specifying regular expressions at the command line, it's preferable to add them to user-fixes.py</tt>

python replace.py -file:articles_list.txt -fix:example2

Example: Replacing multiple paragraphs
The original text of the page Sandbox is: This page is for any tests.

Welcome to the sandbox!

If you want to switch the statement (the second one goes before the first one), you type the following syntax: <pre style="overflow:auto">replace.py -page:Meta:Sandbox -regex "This page is for any tests.\r\n\r\nWelcome to the sandbox!" "Welcome to the sandbox!\n\nThis page is for any tests."

To add a new line we use.

Example: Gathering articles
With -save</tt> one can make fake replacements, what gives the possibility to collect articles that do or do not contain a certain text. In Hungarian Wikipedia a user wanted a list of articles of animals that do not have a template, and a second one of those that don't have the template but have the string "iucnredlist.org" (because they are likely to be linked to the Red List but not with a template). In the examples "Állatfajok" means "animal species":

1. Gathering articles from animal categories that contain "iucnredlist.org" but don't contain the template: replace.py -catr:"Állatfajok" iucnredlist.org b -excepttext:"{{redlist" -save:redlist.txt This would replace "iucnredlist.org" with a letter b</tt>, but instead of modifying pages saves their titles to redlist.txt. (Sure, we are bot owners and not vandals!)

2. Gathering articles from animal categories that contain neither "iucnredlist.org" nor the template: replace.py -catr:"Állatfajok" e b -excepttext:iucnredlist.org -excepttext:"{{redlist" -save:redlist.txt If both texts are on exception list, what do we search for? For example the most frequent vowel of Hungarian language, e</tt>. We don't risk too much by assuming that every article contains it. :-)

If we want to avoid listing articles with upper case {{Redlist}} templates, we need either an additional exception or regular expression.

Example: Plenty of unbolding within an article
In this article there were really lot of bolded episode titles in several tables that were to be unbolded. This is the case when you may want to use a bot for one single article and this shows the role of some interesting parameters.


 * What are we looking for?
 * Texts between pairs of  ''' </tt>,
 * which are within a table (we don't want to replace in the rest of the article!),
 * but do not contain a  | </tt> character (just for safety, to make sure we are still within one cell — we might perhaps omit this),
 * paying attention to having many occurrences within a table (recursion),
 * and that the tables are wrapped to several lines (dotall),
 * and that every table opening tag should match its own closing tag and every beginning of bold text should match its own closing  ''' </tt> (that's why we use ?</tt>s to make the expressions ungreedy).

With the text parts before, between and after the boldings — these are put in parentheses to be able to refer to them with their group numbers, respectively.
 * What do we replace it with?

(It is wrapped here for readability, but you should write to one line, of course.) replace.py -page -regex -recursive -dotall -summary:Vastagtalanítás "(\{\|.*?)([^\|]*?)(.*?\|\})" "\1\2\3" The bot will ask for the title since we have not given it. Using double quotation marks fits to the command line and gives the freedom to use apostrophes in the expression.
 * The command

Here you are. (Don't click if your computer is not strong enough!)
 * Result:

Advanced use of fixes: own functions
Being a wizard by means of replace.py is not a dream if you are familiar with the basics of Python programming. textlib.py (another module of the Pywikipedia framework) has a wonderful but not widely used ability. If you write a function instead of a constant text or a regular expression to the replacement text or the exceptions, it will recognize and execute it. With a little bit of programming you may take advantage of this feature, and use replace.py at a higher level. Needless to say, using an own function gives much more flexibility than a simple regex. You may also use a function to generate the replacement expressions so as to keep them clearly arranged.

To learn how to use your own functions in fixes.py and user-fixes.py and what is this good for, see hu:Szerkesztő:Bináris/Fixes and functions HOWTO.