rest25/library/difflib.rst => rest262/library/difflib.rst
n1- 
2:mod:`difflib` --- Helpers for computing deltas
3===============================================
4
5.. module:: difflib
6   :synopsis: Helpers for computing differences between objects.
7.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
8.. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>
n9- 
10- 
11-.. % LaTeXification by Fred L. Drake, Jr. <fdrake@acm.org>.
8+.. Markup by Fred L. Drake, Jr. <fdrake@acm.org>
9+ 
10+.. testsetup::
11+ 
12+   import sys
13+   from difflib import *
12
13.. versionadded:: 2.1
14
n17+This module provides classes and functions for comparing sequences. It
18+can be used for example, for comparing files, and can produce difference
19+information in various formats, including HTML and context and unified
20+diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
15
16.. class:: SequenceMatcher
17
18   This is a flexible class for comparing pairs of sequences of any type, so long
n19-   as the sequence elements are hashable.  The basic algorithm predates, and is a
n25+   as the sequence elements are :term:`hashable`.  The basic algorithm predates, and is a
20   little fancier than, an algorithm published in the late 1980's by Ratcliff and
21   Obershelp under the hyperbolic name "gestalt pattern matching."  The idea is to
22   find the longest contiguous matching subsequence that contains no "junk"
23   elements (the Ratcliff and Obershelp algorithm doesn't address junk).  The same
24   idea is then applied recursively to the pieces of the sequences to the left and
25   to the right of the matching subsequence.  This does not yield minimal edit
26   sequences, but does tend to yield matches that "look right" to people.
27
29   case and quadratic time in the expected case. :class:`SequenceMatcher` is
30   quadratic time for the worst case and has expected-case behavior dependent in a
31   complicated way on how many elements the sequences have in common; best case
32   time is linear.
33
34
35.. class:: Differ
36
n37-   This is a class for comparing sequences of lines of text, and producing human-
n43+   This is a class for comparing sequences of lines of text, and producing
38-   readable differences or deltas.  Differ uses :class:`SequenceMatcher` both to
44+   human-readable differences or deltas.  Differ uses :class:`SequenceMatcher`
39-   compare sequences of lines, and to compare sequences of characters within
45+   both to compare sequences of lines, and to compare sequences of characters
40-   similar (near-matching) lines.
46+   within similar (near-matching) lines.
41
42   Each line of a :class:`Differ` delta begins with a two-letter code:
43
44   +----------+-------------------------------------------+
45   | Code     | Meaning                                   |
46   +==========+===========================================+
47   | ``'- '`` | line unique to sequence 1                 |
48   +----------+-------------------------------------------+
117   :file:`Tools/scripts/diff.py` is a command-line front-end to this class and
118   contains a good example of its use.
119
120   .. versionadded:: 2.4
121
122
123.. function:: context_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
124
n125-   Compare *a* and *b* (lists of strings); return a delta (a generator generating
n131+   Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
126-   the delta lines) in context diff format.
132+   generating the delta lines) in context diff format.
127
128   Context diffs are a compact way of showing just the lines that have changed plus
129   a few lines of context.  The changes are shown in a before/after style.  The
130   number of context lines is set by *n* which defaults to three.
131
132   By default, the diff control lines (those with ``***`` or ``---``) are created
133   with a trailing newline.  This is helpful so that inputs created from
134   :func:`file.readlines` result in diffs that are suitable for use with
139   ``""`` so that the output will be uniformly newline free.
140
141   The context diff format normally has a header for filenames and modification
142   times.  Any or all of these may be specified using strings for *fromfile*,
143   *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
144   expressed in the format returned by :func:`time.ctime`.  If not specified, the
145   strings default to blanks.
146
n147-   :file:`Tools/scripts/diff.py` is a command-line front-end for this function.
n153+      >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
154+      >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
155+      >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
156+      ...     sys.stdout.write(line)  # doctest: +NORMALIZE_WHITESPACE
157+      *** before.py
158+      --- after.py
159+      ***************
160+      *** 1,4 ****
161+      ! bacon
162+      ! eggs
163+      ! ham
164+        guido
165+      --- 1,4 ----
166+      ! python
167+      ! eggy
168+      ! hamster
169+        guido
170+ 
171+   See :ref:`difflib-interface` for a more detailed example.
148
149   .. versionadded:: 2.3
150
151
152.. function:: get_close_matches(word, possibilities[, n][, cutoff])
153
154   Return a list of the best "good enough" matches.  *word* is a sequence for which
155   close matches are desired (typically a string), and *possibilities* is a list of
157
158   Optional argument *n* (default ``3``) is the maximum number of close matches to
159   return; *n* must be greater than ``0``.
160
161   Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
162   Possibilities that don't score at least that similar to *word* are ignored.
163
164   The best (no more than *n*) matches among the possibilities are returned in a
n165-   list, sorted by similarity score, most similar first. ::
n189+   list, sorted by similarity score, most similar first.
166
167      >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
168      ['apple', 'ape']
169      >>> import keyword
170      >>> get_close_matches('wheel', keyword.kwlist)
171      ['while']
172      >>> get_close_matches('apple', keyword.kwlist)
173      []
174      >>> get_close_matches('accept', keyword.kwlist)
175      ['except']
176
177
178.. function:: ndiff(a, b[, linejunk][, charjunk])
179
n180-   Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style delta
n204+   Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
181-   (a generator generating the delta lines).
205+   delta (a :term:`generator` generating the delta lines).
182
183   Optional keyword parameters *linejunk* and *charjunk* are for filter functions
184   (or ``None``):
185
186   *linejunk*: A function that accepts a single string argument, and returns true
187   if the string is junk, or false if not. The default is (``None``), starting with
188   Python 2.3.  Before then, the default was the module-level function
189   :func:`IS_LINE_JUNK`, which filters out lines without visible characters, except
192   frequent as to constitute noise, and this usually works better than the pre-2.3
193   default.
194
195   *charjunk*: A function that accepts a character (a string of length 1), and
196   returns if the character is junk, or false if not. The default is module-level
197   function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
198   blank or tab; note: bad idea to include newline in this!).
199
n200-   :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function. ::
n224+   :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.
201
202      >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
203      ...              'ore\ntree\nemu\n'.splitlines(1))
204      >>> print ''.join(diff),
205      - one
206      ?  ^
207      + ore
208      ?  ^
216.. function:: restore(sequence, which)
217
218   Return one of the two sequences that generated a delta.
219
220   Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
221   lines originating from file 1 or 2 (parameter *which*), stripping off line
222   prefixes.
223
n224-   Example::
n248+   Example:
225
226      >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
227      ...              'ore\ntree\nemu\n'.splitlines(1))
228      >>> diff = list(diff) # materialize the generated delta into a list
229      >>> print ''.join(restore(diff, 1)),
230      one
231      two
232      three
233      >>> print ''.join(restore(diff, 2)),
234      ore
235      tree
236      emu
237
238
239.. function:: unified_diff(a, b[, fromfile][, tofile][, fromfiledate][, tofiledate][, n][, lineterm])
240
n241-   Compare *a* and *b* (lists of strings); return a delta (a generator generating
n265+   Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
242-   the delta lines) in unified diff format.
266+   generating the delta lines) in unified diff format.
243
244   Unified diffs are a compact way of showing just the lines that have changed plus
245   a few lines of context.  The changes are shown in a inline style (instead of
246   separate before/after blocks).  The number of context lines is set by *n* which
247   defaults to three.
248
249   By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
250   created with a trailing newline.  This is helpful so that inputs created from
256   ``""`` so that the output will be uniformly newline free.
257
258   The context diff format normally has a header for filenames and modification
259   times.  Any or all of these may be specified using strings for *fromfile*,
260   *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
261   expressed in the format returned by :func:`time.ctime`.  If not specified, the
262   strings default to blanks.
263
n264-   :file:`Tools/scripts/diff.py` is a command-line front-end for this function.
n288+      >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
289+      >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
290+      >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
291+      ...     sys.stdout.write(line)   # doctest: +NORMALIZE_WHITESPACE
292+      --- before.py
293+      +++ after.py
294+      @@ -1,4 +1,4 @@
295+      -bacon
296+      -eggs
297+      -ham
298+      +python
299+      +eggy
300+      +hamster
301+       guido
302+ 
303+   See :ref:`difflib-interface` for a more detailed example.
265
266   .. versionadded:: 2.3
267
268
269.. function:: IS_LINE_JUNK(line)
270
271   Return true for ignorable lines.  The line *line* is ignorable if *line* is
272   blank or contains a single ``'#'``, otherwise it is not ignorable.  Used as a
277
278   Return true for ignorable characters.  The character *ch* is ignorable if *ch*
279   is a space or tab, otherwise it is not ignorable.  Used as a default for
280   parameter *charjunk* in :func:`ndiff`.
281
282
283.. seealso::
284
n285-   `Pattern Matching: The Gestalt Approach <http://www.ddj.com/documents/s=1103/ddj8807c/>`_
n324+   `Pattern Matching: The Gestalt Approach <http://www.ddj.com/184407970?pgno=5>`_
286      Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
287      was published in `Dr. Dobb's Journal <http://www.ddj.com/>`_ in July, 1988.
288
289
290.. _sequence-matcher:
291
292SequenceMatcher Objects
293-----------------------
304   For example, pass::
305
306      lambda x: x in " \t"
307
308   if you're comparing lines as sequences of characters, and don't want to synch up
309   on blanks or hard tabs.
310
311   The optional arguments *a* and *b* are sequences to be compared; both default to
n312-   empty strings.  The elements of both sequences must be hashable.
n351+   empty strings.  The elements of both sequences must be :term:`hashable`.
313
n314-:class:`SequenceMatcher` objects have the following methods:
n353+   :class:`SequenceMatcher` objects have the following methods:
315
316
n317-.. method:: SequenceMatcher.set_seqs(a, b)
n356+   .. method:: set_seqs(a, b)
318
n319-   Set the two sequences to be compared.
n358+      Set the two sequences to be compared.
320
n321-:class:`SequenceMatcher` computes and caches detailed information about the
n360+   :class:`SequenceMatcher` computes and caches detailed information about the
322-second sequence, so if you want to compare one sequence against many sequences,
361+   second sequence, so if you want to compare one sequence against many
323-use :meth:`set_seq2` to set the commonly used sequence once and call
362+   sequences, use :meth:`set_seq2` to set the commonly used sequence once and
324-:meth:`set_seq1` repeatedly, once for each of the other sequences.
363+   call :meth:`set_seq1` repeatedly, once for each of the other sequences.
325
326
n327-.. method:: SequenceMatcher.set_seq1(a)
n366+   .. method:: set_seq1(a)
328
n329-   Set the first sequence to be compared.  The second sequence to be compared is
n368+      Set the first sequence to be compared.  The second sequence to be compared
330-   not changed.
369+      is not changed.
331
332
n333-.. method:: SequenceMatcher.set_seq2(b)
n372+   .. method:: set_seq2(b)
334
n335-   Set the second sequence to be compared.  The first sequence to be compared is
n374+      Set the second sequence to be compared.  The first sequence to be compared
336-   not changed.
375+      is not changed.
337
338
n339-.. method:: SequenceMatcher.find_longest_match(alo, ahi, blo, bhi)
n378+   .. method:: find_longest_match(alo, ahi, blo, bhi)
340
n341-   Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
n380+      Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
342
n343-   If *isjunk* was omitted or ``None``, :meth:`get_longest_match` returns ``(i, j,
n382+      If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
344-   k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo <= i <= i+k <=
383+      ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
345-   ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', k')`` meeting those
384+      <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
346-   conditions, the additional conditions ``k >= k'``, ``i <= i'``, and if ``i ==
385+      k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
347-   i'``, ``j <= j'`` are also met. In other words, of all maximal matching blocks,
386+      <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
348-   return one that starts earliest in *a*, and of all those maximal matching blocks
387+      all maximal matching blocks, return one that starts earliest in *a*, and
349-   that start earliest in *a*, return the one that starts earliest in *b*. ::
388+      of all those maximal matching blocks that start earliest in *a*, return
389+      the one that starts earliest in *b*.
350
n351-      >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
n391+         >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
352-      >>> s.find_longest_match(0, 5, 0, 9)
392+         >>> s.find_longest_match(0, 5, 0, 9)
353-      (0, 4, 5)
393+         Match(a=0, b=4, size=5)
354
n355-   If *isjunk* was provided, first the longest matching block is determined as
n395+      If *isjunk* was provided, first the longest matching block is determined
356-   above, but with the additional restriction that no junk element appears in the
396+      as above, but with the additional restriction that no junk element appears
357-   block.  Then that block is extended as far as possible by matching (only) junk
397+      in the block.  Then that block is extended as far as possible by matching
358-   elements on both sides. So the resulting block never matches on junk except as
398+      (only) junk elements on both sides. So the resulting block never matches
359-   identical junk happens to be adjacent to an interesting match.
399+      on junk except as identical junk happens to be adjacent to an interesting
400+      match.
360
n361-   Here's the same example as before, but considering blanks to be junk. That
n402+      Here's the same example as before, but considering blanks to be junk. That
362-   prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the second
403+      prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
363-   sequence directly.  Instead only the ``'abcd'`` can match, and matches the
404+      second sequence directly.  Instead only the ``'abcd'`` can match, and
364-   leftmost ``'abcd'`` in the second sequence::
405+      matches the leftmost ``'abcd'`` in the second sequence:
365
n366-      >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
n407+         >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
367-      >>> s.find_longest_match(0, 5, 0, 9)
408+         >>> s.find_longest_match(0, 5, 0, 9)
368-      (1, 0, 4)
409+         Match(a=1, b=0, size=4)
369
n370-   If no blocks match, this returns ``(alo, blo, 0)``.
n411+      If no blocks match, this returns ``(alo, blo, 0)``.
371
n413+      .. versionchanged:: 2.6
414+         This method returns a :term:`named tuple` ``Match(a, b, size)``.
372
n416+ 
373-.. method:: SequenceMatcher.get_matching_blocks()
417+   .. method:: get_matching_blocks()
374
n375-   Return list of triples describing matching subsequences. Each triple is of the
n419+      Return list of triples describing matching subsequences. Each triple is of
376-   form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``.  The triples are
420+      the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``.  The
377-   monotonically increasing in *i* and *j*.
421+      triples are monotonically increasing in *i* and *j*.
378
n379-   The last triple is a dummy, and has the value ``(len(a), len(b), 0)``.  It is
n423+      The last triple is a dummy, and has the value ``(len(a), len(b), 0)``.  It
380-   the only triple with ``n == 0``.  If ``(i, j, n)`` and ``(i', j', n')`` are
424+      is the only triple with ``n == 0``.  If ``(i, j, n)`` and ``(i', j', n')``
381-   adjacent triples in the list, and the second is not the last triple in the list,
425+      are adjacent triples in the list, and the second is not the last triple in
382-   then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent triples always
426+      the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
383-   describe non-adjacent equal blocks.
427+      triples always describe non-adjacent equal blocks.
384
n385-   .. % Explain why a dummy is used!
n429+      .. XXX Explain why a dummy is used!
386
n387-   .. versionchanged:: 2.5
n431+      .. versionchanged:: 2.5
388-      The guarantee that adjacent triples always describe non-adjacent blocks was
432+         The guarantee that adjacent triples always describe non-adjacent blocks
389-      implemented.
433+         was implemented.
390
n391-   ::
n435+      .. doctest::
392
n393-      >>> s = SequenceMatcher(None, "abxcd", "abcd")
n437+         >>> s = SequenceMatcher(None, "abxcd", "abcd")
394-      >>> s.get_matching_blocks()
438+         >>> s.get_matching_blocks()
395-      [(0, 0, 2), (3, 2, 2), (5, 4, 0)]
439+         [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
396
397
n398-.. method:: SequenceMatcher.get_opcodes()
n442+   .. method:: get_opcodes()
399
n400-   Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is of
n444+      Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
401-   the form ``(tag, i1, i2, j1, j2)``.  The first tuple has ``i1 == j1 == 0``, and
445+      of the form ``(tag, i1, i2, j1, j2)``.  The first tuple has ``i1 == j1 ==
402-   remaining tuples have *i1* equal to the *i2* from the preceding tuple, and,
446+      0``, and remaining tuples have *i1* equal to the *i2* from the preceding
403-   likewise, *j1* equal to the previous *j2*.
447+      tuple, and, likewise, *j1* equal to the previous *j2*.
404
n405-   The *tag* values are strings, with these meanings:
n449+      The *tag* values are strings, with these meanings:
406
n407-   +---------------+---------------------------------------------+
n451+      +---------------+---------------------------------------------+
408-   | Value         | Meaning                                     |
452+      | Value         | Meaning                                     |
409-   +===============+=============================================+
453+      +===============+=============================================+
410-   | ``'replace'`` | ``a[i1:i2]`` should be replaced by          |
454+      | ``'replace'`` | ``a[i1:i2]`` should be replaced by          |
411-   |               | ``b[j1:j2]``.                               |
455+      |               | ``b[j1:j2]``.                               |
412-   +---------------+---------------------------------------------+
456+      +---------------+---------------------------------------------+
413-   | ``'delete'``  | ``a[i1:i2]`` should be deleted.  Note that  |
457+      | ``'delete'``  | ``a[i1:i2]`` should be deleted.  Note that  |
414-   |               | ``j1 == j2`` in this case.                  |
458+      |               | ``j1 == j2`` in this case.                  |
415-   +---------------+---------------------------------------------+
459+      +---------------+---------------------------------------------+
416-   | ``'insert'``  | ``b[j1:j2]`` should be inserted at          |
460+      | ``'insert'``  | ``b[j1:j2]`` should be inserted at          |
417-   |               | ``a[i1:i1]``. Note that ``i1 == i2`` in     |
461+      |               | ``a[i1:i1]``. Note that ``i1 == i2`` in     |
418-   |               | this case.                                  |
462+      |               | this case.                                  |
419-   +---------------+---------------------------------------------+
463+      +---------------+---------------------------------------------+
420-   | ``'equal'``   | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
464+      | ``'equal'``   | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
421-   |               | are equal).                                 |
465+      |               | are equal).                                 |
422-   +---------------+---------------------------------------------+
466+      +---------------+---------------------------------------------+
423
n424-   For example::
n468+      For example:
425
n426-      >>> a = "qabxcd"
n470+         >>> a = "qabxcd"
427-      >>> b = "abycdf"
471+         >>> b = "abycdf"
428-      >>> s = SequenceMatcher(None, a, b)
472+         >>> s = SequenceMatcher(None, a, b)
429-      >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
473+         >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
430-      ...    print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
474+         ...    print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
431-      ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
475+         ...           (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
432-       delete a[0:1] (q) b[0:0] ()
476+          delete a[0:1] (q) b[0:0] ()
433-        equal a[1:3] (ab) b[0:2] (ab)
477+           equal a[1:3] (ab) b[0:2] (ab)
434-      replace a[3:4] (x) b[2:3] (y)
478+         replace a[3:4] (x) b[2:3] (y)
435-        equal a[4:6] (cd) b[3:5] (cd)
479+           equal a[4:6] (cd) b[3:5] (cd)
436-       insert a[6:6] () b[5:6] (f)
480+          insert a[6:6] () b[5:6] (f)
437
438
n439-.. method:: SequenceMatcher.get_grouped_opcodes([n])
n483+   .. method:: get_grouped_opcodes([n])
440
n441-   Return a generator of groups with up to *n* lines of context.
n485+      Return a :term:`generator` of groups with up to *n* lines of context.
442
n443-   Starting with the groups returned by :meth:`get_opcodes`, this method splits out
n487+      Starting with the groups returned by :meth:`get_opcodes`, this method
444-   smaller change clusters and eliminates intervening ranges which have no changes.
488+      splits out smaller change clusters and eliminates intervening ranges which
489+      have no changes.
445
n446-   The groups are returned in the same format as :meth:`get_opcodes`.
n491+      The groups are returned in the same format as :meth:`get_opcodes`.
447
n448-   .. versionadded:: 2.3
n493+      .. versionadded:: 2.3
449
450
n451-.. method:: SequenceMatcher.ratio()
n496+   .. method:: ratio()
452
n453-   Return a measure of the sequences' similarity as a float in the range [0, 1].
n498+      Return a measure of the sequences' similarity as a float in the range [0,
499+      1].
454
n455-   Where T is the total number of elements in both sequences, and M is the number
n501+      Where T is the total number of elements in both sequences, and M is the
456-   of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the sequences are
502+      number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
457-   identical, and ``0.0`` if they have nothing in common.
503+      sequences are identical, and ``0.0`` if they have nothing in common.
458
n459-   This is expensive to compute if :meth:`get_matching_blocks` or
n505+      This is expensive to compute if :meth:`get_matching_blocks` or
460-   :meth:`get_opcodes` hasn't already been called, in which case you may want to
506+      :meth:`get_opcodes` hasn't already been called, in which case you may want
461-   try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an upper bound.
507+      to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
508+      upper bound.
462
463
n464-.. method:: SequenceMatcher.quick_ratio()
n511+   .. method:: quick_ratio()
465
n466-   Return an upper bound on :meth:`ratio` relatively quickly.
n513+      Return an upper bound on :meth:`ratio` relatively quickly.
467
n468-   This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is
n515+      This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
469-   faster to compute.
516+      is faster to compute.
470
471
n472-.. method:: SequenceMatcher.real_quick_ratio()
n519+   .. method:: real_quick_ratio()
473
n474-   Return an upper bound on :meth:`ratio` very quickly.
n521+      Return an upper bound on :meth:`ratio` very quickly.
475
n476-   This isn't defined beyond that it is an upper bound on :meth:`ratio`, and is
n523+      This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
477-   faster to compute than either :meth:`ratio` or :meth:`quick_ratio`.
524+      is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`.
478
479The three methods that return the ratio of matching to total characters can give
480different results due to differing levels of approximation, although
481:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
n482-:meth:`ratio`::
n529+:meth:`ratio`:
483
484   >>> s = SequenceMatcher(None, "abcd", "bcde")
485   >>> s.ratio()
486   0.75
487   >>> s.quick_ratio()
488   0.75
489   >>> s.real_quick_ratio()
490   1.0
491
492
493.. _sequencematcher-examples:
494
495SequenceMatcher Examples
496------------------------
497
n498-This example compares two strings, considering blanks to be "junk:" ::
n545+This example compares two strings, considering blanks to be "junk:"
499
500   >>> s = SequenceMatcher(lambda x: x == " ",
501   ...                     "private Thread currentThread;",
502   ...                     "private volatile Thread currentThread;")
503
504:meth:`ratio` returns a float in [0, 1], measuring the similarity of the
505sequences.  As a rule of thumb, a :meth:`ratio` value over 0.6 means the
n506-sequences are close matches::
n553+sequences are close matches:
507
508   >>> print round(s.ratio(), 3)
509   0.866
510
511If you're only interested in where the sequences match,
n512-:meth:`get_matching_blocks` is handy::
n559+:meth:`get_matching_blocks` is handy:
513
514   >>> for block in s.get_matching_blocks():
515   ...     print "a[%d] and b[%d] match for %d elements" % block
516   a[0] and b[0] match for 8 elements
n517-   a[8] and b[17] match for 6 elements
n564+   a[8] and b[17] match for 21 elements
518-   a[14] and b[23] match for 15 elements
519   a[29] and b[38] match for 0 elements
520
521Note that the last tuple returned by :meth:`get_matching_blocks` is always a
522dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
523tuple element (number of elements matched) is ``0``.
524
525If you want to know how to change the first sequence into the second, use
n526-:meth:`get_opcodes`::
n572+:meth:`get_opcodes`:
527
528   >>> for opcode in s.get_opcodes():
529   ...     print "%6s a[%d:%d] b[%d:%d]" % opcode
530    equal a[0:8] b[0:8]
531   insert a[8:8] b[8:17]
n532-    equal a[8:14] b[17:23]
n578+    equal a[8:29] b[17:38]
533-    equal a[14:29] b[23:38]
534
535See also the function :func:`get_close_matches` in this module, which shows how
536simple code building on :class:`SequenceMatcher` can be used to do useful work.
537
538
539.. _differ-objects:
540
541Differ Objects
558   *linejunk*: A function that accepts a single string argument, and returns true
559   if the string is junk.  The default is ``None``, meaning that no line is
560   considered junk.
561
562   *charjunk*: A function that accepts a single character argument (a string of
563   length 1), and returns true if the character is junk. The default is ``None``,
564   meaning that no character is considered junk.
565
n566-:class:`Differ` objects are used (deltas generated) via a single method:
n611+   :class:`Differ` objects are used (deltas generated) via a single method:
567
568
n569-.. method:: Differ.compare(a, b)
n614+   .. method:: Differ.compare(a, b)
570
n571-   Compare two sequences of lines, and generate the delta (a sequence of lines).
n616+      Compare two sequences of lines, and generate the delta (a sequence of lines).
572
n573-   Each sequence must contain individual single-line strings ending with newlines.
n618+      Each sequence must contain individual single-line strings ending with newlines.
574-   Such sequences can be obtained from the :meth:`readlines` method of file-like
619+      Such sequences can be obtained from the :meth:`readlines` method of file-like
575-   objects.  The delta generated also consists of newline-terminated strings, ready
620+      objects.  The delta generated also consists of newline-terminated strings, ready
576-   to be printed as-is via the :meth:`writelines` method of a file-like object.
621+      to be printed as-is via the :meth:`writelines` method of a file-like object.
577
578
579.. _differ-examples:
580
581Differ Example
582--------------
583
584This example compares two texts. First we set up the texts, sequences of
585individual single-line strings ending with newlines (such sequences can also be
n586-obtained from the :meth:`readlines` method of file-like objects)::
n631+obtained from the :meth:`readlines` method of file-like objects):
587
588   >>> text1 = '''  1. Beautiful is better than ugly.
589   ...   2. Explicit is better than implicit.
590   ...   3. Simple is better than complex.
591   ...   4. Complex is better than complicated.
592   ... '''.splitlines(1)
593   >>> len(text1)
594   4
595   >>> text1[0][-1]
596   '\n'
597   >>> text2 = '''  1. Beautiful is better than ugly.
598   ...   3.   Simple is better than complex.
599   ...   4. Complicated is better than complex.
600   ...   5. Flat is better than nested.
601   ... '''.splitlines(1)
602
n603-Next we instantiate a Differ object::
n648+Next we instantiate a Differ object:
604
605   >>> d = Differ()
606
607Note that when instantiating a :class:`Differ` object we may pass functions to
608filter out line and character "junk."  See the :meth:`Differ` constructor for
609details.
610
n611-Finally, we compare the two::
n656+Finally, we compare the two:
612
613   >>> result = list(d.compare(text1, text2))
614
n615-``result`` is a list of strings, so let's pretty-print it::
n660+``result`` is a list of strings, so let's pretty-print it:
616
617   >>> from pprint import pprint
618   >>> pprint(result)
619   ['    1. Beautiful is better than ugly.\n',
620    '-   2. Explicit is better than implicit.\n',
621    '-   3. Simple is better than complex.\n',
622    '+   3.   Simple is better than complex.\n',
n623-    '?     ++                                \n',
n668+    '?     ++\n',
624    '-   4. Complex is better than complicated.\n',
n625-    '?            ^                     ---- ^  \n',
n670+    '?            ^                     ---- ^\n',
626    '+   4. Complicated is better than complex.\n',
n627-    '?           ++++ ^                      ^  \n',
n672+    '?           ++++ ^                      ^\n',
628    '+   5. Flat is better than nested.\n']
629
n630-As a single multi-line string it looks like this::
n675+As a single multi-line string it looks like this:
631
632   >>> import sys
633   >>> sys.stdout.writelines(result)
634       1. Beautiful is better than ugly.
635   -   2. Explicit is better than implicit.
636   -   3. Simple is better than complex.
637   +   3.   Simple is better than complex.
638   ?     ++
639   -   4. Complex is better than complicated.
640   ?            ^                     ---- ^
641   +   4. Complicated is better than complex.
642   ?           ++++ ^                      ^
643   +   5. Flat is better than nested.
644
t690+ 
691+.. _difflib-interface:
692+ 
693+A command-line interface to difflib
694+-----------------------------------
695+ 
696+This example shows how to use difflib to create a ``diff``-like utility.
697+It is also contained in the Python source distribution, as
698+:file:`Tools/scripts/diff.py`.
699+ 
700+.. testcode::
701+ 
702+   """ Command line interface to difflib.py providing diffs in four formats:
703+ 
704+   * ndiff:    lists every line and highlights interline changes.
705+   * context:  highlights clusters of changes in a before/after format.
706+   * unified:  highlights clusters of changes in an inline format.
707+   * html:     generates side by side comparison with change highlights.
708+ 
709+   """
710+ 
711+   import sys, os, time, difflib, optparse
712+ 
713+   def main():
714+        # Configure the option parser
715+       usage = "usage: %prog [options] fromfile tofile"
716+       parser = optparse.OptionParser(usage)
717+       parser.add_option("-c", action="store_true", default=False,
718+                         help='Produce a context format diff (default)')
719+       parser.add_option("-u", action="store_true", default=False,
720+                         help='Produce a unified format diff')
721+       hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)'
722+       parser.add_option("-m", action="store_true", default=False, help=hlp)
723+       parser.add_option("-n", action="store_true", default=False,
724+                         help='Produce a ndiff format diff')
725+       parser.add_option("-l", "--lines", type="int", default=3,
726+                         help='Set number of context lines (default 3)')
727+       (options, args) = parser.parse_args()
728+ 
729+       if len(args) == 0:
730+           parser.print_help()
731+           sys.exit(1)
732+       if len(args) != 2:
733+           parser.error("need to specify both a fromfile and tofile")
734+ 
735+       n = options.lines
736+       fromfile, tofile = args # as specified in the usage string
737+ 
738+       # we're passing these as arguments to the diff function
739+       fromdate = time.ctime(os.stat(fromfile).st_mtime)
740+       todate = time.ctime(os.stat(tofile).st_mtime)
741+       fromlines = open(fromfile, 'U').readlines()
742+       tolines = open(tofile, 'U').readlines()
743+ 
744+       if options.u:
745+           diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,
746+                                       fromdate, todate, n=n)
747+       elif options.n:
748+           diff = difflib.ndiff(fromlines, tolines)
749+       elif options.m:
750+           diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
751+                                               tofile, context=options.c,
752+                                               numlines=n)
753+       else:
754+           diff = difflib.context_diff(fromlines, tolines, fromfile, tofile,
755+                                       fromdate, todate, n=n)
756+ 
757+       # we're using writelines because diff is a generator
758+       sys.stdout.writelines(diff)
759+ 
760+   if __name__ == '__main__':
761+       main()
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op