blob: c7efa967b00c97ec437ac035100a6c470013967f [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`difflib` --- Helpers for computing deltas
2===============================================
3
4.. module:: difflib
5 :synopsis: Helpers for computing differences between objects.
6.. moduleauthor:: Tim Peters <tim_one@users.sourceforge.net>
7.. sectionauthor:: Tim Peters <tim_one@users.sourceforge.net>
Christian Heimes5b5e81c2007-12-31 16:14:33 +00008.. Markup by Fred L. Drake, Jr. <fdrake@acm.org>
Georg Brandl116aa622007-08-15 14:28:22 +00009
Christian Heimesfe337bf2008-03-23 21:54:12 +000010.. testsetup::
Georg Brandl116aa622007-08-15 14:28:22 +000011
Christian Heimesfe337bf2008-03-23 21:54:12 +000012 import sys
13 from difflib import *
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl9afde1c2007-11-01 20:32:30 +000015This module provides classes and functions for comparing sequences. It
16can be used for example, for comparing files, and can produce difference
17information in various formats, including HTML and context and unified
18diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
19
Terry Reedy99f96372010-11-25 06:12:34 +000020
Georg Brandl116aa622007-08-15 14:28:22 +000021.. class:: SequenceMatcher
22
23 This is a flexible class for comparing pairs of sequences of any type, so long
Guido van Rossum2cc30da2007-11-02 23:46:40 +000024 as the sequence elements are :term:`hashable`. The basic algorithm predates, and is a
Georg Brandl116aa622007-08-15 14:28:22 +000025 little fancier than, an algorithm published in the late 1980's by Ratcliff and
26 Obershelp under the hyperbolic name "gestalt pattern matching." The idea is to
27 find the longest contiguous matching subsequence that contains no "junk"
28 elements (the Ratcliff and Obershelp algorithm doesn't address junk). The same
29 idea is then applied recursively to the pieces of the sequences to the left and
30 to the right of the matching subsequence. This does not yield minimal edit
31 sequences, but does tend to yield matches that "look right" to people.
32
33 **Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the worst
34 case and quadratic time in the expected case. :class:`SequenceMatcher` is
35 quadratic time for the worst case and has expected-case behavior dependent in a
36 complicated way on how many elements the sequences have in common; best case
37 time is linear.
38
Terry Reedy99f96372010-11-25 06:12:34 +000039 **Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic that
40 automatically treats certain sequence items as junk. The heuristic counts how many
41 times each individual item appears in the sequence. If an item's duplicates (after
42 the first one) account for more than 1% of the sequence and the sequence is at least
43 200 items long, this item is marked as "popular" and is treated as junk for
44 the purpose of sequence matching. This heuristic can be turned off by setting
45 the ``autojunk`` argument to ``False`` when creating the :class:`SequenceMatcher`.
46
Georg Brandl116aa622007-08-15 14:28:22 +000047
48.. class:: Differ
49
50 This is a class for comparing sequences of lines of text, and producing
51 human-readable differences or deltas. Differ uses :class:`SequenceMatcher`
52 both to compare sequences of lines, and to compare sequences of characters
53 within similar (near-matching) lines.
54
55 Each line of a :class:`Differ` delta begins with a two-letter code:
56
57 +----------+-------------------------------------------+
58 | Code | Meaning |
59 +==========+===========================================+
60 | ``'- '`` | line unique to sequence 1 |
61 +----------+-------------------------------------------+
62 | ``'+ '`` | line unique to sequence 2 |
63 +----------+-------------------------------------------+
64 | ``' '`` | line common to both sequences |
65 +----------+-------------------------------------------+
66 | ``'? '`` | line not present in either input sequence |
67 +----------+-------------------------------------------+
68
69 Lines beginning with '``?``' attempt to guide the eye to intraline differences,
70 and were not present in either input sequence. These lines can be confusing if
71 the sequences contain tab characters.
72
73
74.. class:: HtmlDiff
75
76 This class can be used to create an HTML table (or a complete HTML file
77 containing the table) showing a side by side, line by line comparison of text
78 with inter-line and intra-line change highlights. The table can be generated in
79 either full or contextual difference mode.
80
81 The constructor for this class is:
82
83
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000084 .. method:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 Initializes instance of :class:`HtmlDiff`.
87
88 *tabsize* is an optional keyword argument to specify tab stop spacing and
89 defaults to ``8``.
90
91 *wrapcolumn* is an optional keyword to specify column number where lines are
92 broken and wrapped, defaults to ``None`` where lines are not wrapped.
93
94 *linejunk* and *charjunk* are optional keyword arguments passed into ``ndiff()``
95 (used by :class:`HtmlDiff` to generate the side by side HTML differences). See
96 ``ndiff()`` documentation for argument default values and descriptions.
97
98 The following methods are public:
99
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000100 .. method:: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102 Compares *fromlines* and *tolines* (lists of strings) and returns a string which
103 is a complete HTML file containing a table showing line by line differences with
104 inter-line and intra-line changes highlighted.
105
106 *fromdesc* and *todesc* are optional keyword arguments to specify from/to file
107 column header strings (both default to an empty string).
108
109 *context* and *numlines* are both optional keyword arguments. Set *context* to
110 ``True`` when contextual differences are to be shown, else the default is
111 ``False`` to show the full files. *numlines* defaults to ``5``. When *context*
112 is ``True`` *numlines* controls the number of context lines which surround the
113 difference highlights. When *context* is ``False`` *numlines* controls the
114 number of lines which are shown before a difference highlight when using the
115 "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place
116 the next difference highlight at the top of the browser without any leading
117 context).
118
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000119 .. method:: make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 Compares *fromlines* and *tolines* (lists of strings) and returns a string which
122 is a complete HTML table showing line by line differences with inter-line and
123 intra-line changes highlighted.
124
125 The arguments for this method are the same as those for the :meth:`make_file`
126 method.
127
128 :file:`Tools/scripts/diff.py` is a command-line front-end to this class and
129 contains a good example of its use.
130
Georg Brandl116aa622007-08-15 14:28:22 +0000131
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000132.. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
Georg Brandl116aa622007-08-15 14:28:22 +0000133
Georg Brandl9afde1c2007-11-01 20:32:30 +0000134 Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
135 generating the delta lines) in context diff format.
Georg Brandl116aa622007-08-15 14:28:22 +0000136
137 Context diffs are a compact way of showing just the lines that have changed plus
138 a few lines of context. The changes are shown in a before/after style. The
139 number of context lines is set by *n* which defaults to three.
140
141 By default, the diff control lines (those with ``***`` or ``---``) are created
142 with a trailing newline. This is helpful so that inputs created from
143 :func:`file.readlines` result in diffs that are suitable for use with
144 :func:`file.writelines` since both the inputs and outputs have trailing
145 newlines.
146
147 For inputs that do not have trailing newlines, set the *lineterm* argument to
148 ``""`` so that the output will be uniformly newline free.
149
150 The context diff format normally has a header for filenames and modification
151 times. Any or all of these may be specified using strings for *fromfile*,
R. David Murrayb2416e52010-04-12 16:58:02 +0000152 *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
153 expressed in the ISO 8601 format. If not specified, the
Georg Brandl116aa622007-08-15 14:28:22 +0000154 strings default to blanks.
155
Christian Heimes8640e742008-02-23 16:23:06 +0000156 >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
157 >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
158 >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
Christian Heimesfe337bf2008-03-23 21:54:12 +0000159 ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
Christian Heimes8640e742008-02-23 16:23:06 +0000160 *** before.py
161 --- after.py
162 ***************
163 *** 1,4 ****
164 ! bacon
165 ! eggs
166 ! ham
167 guido
168 --- 1,4 ----
169 ! python
170 ! eggy
171 ! hamster
172 guido
173
174 See :ref:`difflib-interface` for a more detailed example.
Georg Brandl116aa622007-08-15 14:28:22 +0000175
Georg Brandl116aa622007-08-15 14:28:22 +0000176
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000177.. function:: get_close_matches(word, possibilities, n=3, cutoff=0.6)
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179 Return a list of the best "good enough" matches. *word* is a sequence for which
180 close matches are desired (typically a string), and *possibilities* is a list of
181 sequences against which to match *word* (typically a list of strings).
182
183 Optional argument *n* (default ``3``) is the maximum number of close matches to
184 return; *n* must be greater than ``0``.
185
186 Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
187 Possibilities that don't score at least that similar to *word* are ignored.
188
189 The best (no more than *n*) matches among the possibilities are returned in a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000190 list, sorted by similarity score, most similar first.
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
193 ['apple', 'ape']
194 >>> import keyword
195 >>> get_close_matches('wheel', keyword.kwlist)
196 ['while']
197 >>> get_close_matches('apple', keyword.kwlist)
198 []
199 >>> get_close_matches('accept', keyword.kwlist)
200 ['except']
201
202
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000203.. function:: ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)
Georg Brandl116aa622007-08-15 14:28:22 +0000204
Georg Brandl9afde1c2007-11-01 20:32:30 +0000205 Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
206 delta (a :term:`generator` generating the delta lines).
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208 Optional keyword parameters *linejunk* and *charjunk* are for filter functions
209 (or ``None``):
210
Georg Brandle6bcc912008-05-12 18:05:20 +0000211 *linejunk*: A function that accepts a single string argument, and returns
212 true if the string is junk, or false if not. The default is ``None``. There
213 is also a module-level function :func:`IS_LINE_JUNK`, which filters out lines
214 without visible characters, except for at most one pound character (``'#'``)
215 -- however the underlying :class:`SequenceMatcher` class does a dynamic
216 analysis of which lines are so frequent as to constitute noise, and this
217 usually works better than using this function.
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219 *charjunk*: A function that accepts a character (a string of length 1), and
220 returns if the character is junk, or false if not. The default is module-level
221 function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
222 blank or tab; note: bad idea to include newline in this!).
223
Christian Heimesfe337bf2008-03-23 21:54:12 +0000224 :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.
Georg Brandl116aa622007-08-15 14:28:22 +0000225
226 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
227 ... 'ore\ntree\nemu\n'.splitlines(1))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000228 >>> print(''.join(diff), end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000229 - one
230 ? ^
231 + ore
232 ? ^
233 - two
234 - three
235 ? -
236 + tree
237 + emu
238
239
240.. function:: restore(sequence, which)
241
242 Return one of the two sequences that generated a delta.
243
244 Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
245 lines originating from file 1 or 2 (parameter *which*), stripping off line
246 prefixes.
247
Christian Heimesfe337bf2008-03-23 21:54:12 +0000248 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000249
250 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
251 ... 'ore\ntree\nemu\n'.splitlines(1))
252 >>> diff = list(diff) # materialize the generated delta into a list
Georg Brandl6911e3c2007-09-04 07:15:32 +0000253 >>> print(''.join(restore(diff, 1)), end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000254 one
255 two
256 three
Georg Brandl6911e3c2007-09-04 07:15:32 +0000257 >>> print(''.join(restore(diff, 2)), end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000258 ore
259 tree
260 emu
261
262
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000263.. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandl9afde1c2007-11-01 20:32:30 +0000265 Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
266 generating the delta lines) in unified diff format.
Georg Brandl116aa622007-08-15 14:28:22 +0000267
268 Unified diffs are a compact way of showing just the lines that have changed plus
269 a few lines of context. The changes are shown in a inline style (instead of
270 separate before/after blocks). The number of context lines is set by *n* which
271 defaults to three.
272
273 By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
274 created with a trailing newline. This is helpful so that inputs created from
275 :func:`file.readlines` result in diffs that are suitable for use with
276 :func:`file.writelines` since both the inputs and outputs have trailing
277 newlines.
278
279 For inputs that do not have trailing newlines, set the *lineterm* argument to
280 ``""`` so that the output will be uniformly newline free.
281
282 The context diff format normally has a header for filenames and modification
283 times. Any or all of these may be specified using strings for *fromfile*,
R. David Murrayb2416e52010-04-12 16:58:02 +0000284 *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
285 expressed in the ISO 8601 format. If not specified, the
Georg Brandl116aa622007-08-15 14:28:22 +0000286 strings default to blanks.
287
Christian Heimes8640e742008-02-23 16:23:06 +0000288
289 >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
290 >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
291 >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
Christian Heimesfe337bf2008-03-23 21:54:12 +0000292 ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
Christian Heimes8640e742008-02-23 16:23:06 +0000293 --- before.py
294 +++ after.py
295 @@ -1,4 +1,4 @@
296 -bacon
297 -eggs
298 -ham
299 +python
300 +eggy
301 +hamster
302 guido
303
304 See :ref:`difflib-interface` for a more detailed example.
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Georg Brandl116aa622007-08-15 14:28:22 +0000306
307.. function:: IS_LINE_JUNK(line)
308
309 Return true for ignorable lines. The line *line* is ignorable if *line* is
310 blank or contains a single ``'#'``, otherwise it is not ignorable. Used as a
Georg Brandle6bcc912008-05-12 18:05:20 +0000311 default for parameter *linejunk* in :func:`ndiff` in older versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000312
313
314.. function:: IS_CHARACTER_JUNK(ch)
315
316 Return true for ignorable characters. The character *ch* is ignorable if *ch*
317 is a space or tab, otherwise it is not ignorable. Used as a default for
318 parameter *charjunk* in :func:`ndiff`.
319
320
321.. seealso::
322
323 `Pattern Matching: The Gestalt Approach <http://www.ddj.com/184407970?pgno=5>`_
324 Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
325 was published in `Dr. Dobb's Journal <http://www.ddj.com/>`_ in July, 1988.
326
327
328.. _sequence-matcher:
329
330SequenceMatcher Objects
331-----------------------
332
333The :class:`SequenceMatcher` class has this constructor:
334
335
Terry Reedy99f96372010-11-25 06:12:34 +0000336.. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000337
338 Optional argument *isjunk* must be ``None`` (the default) or a one-argument
339 function that takes a sequence element and returns true if and only if the
340 element is "junk" and should be ignored. Passing ``None`` for *isjunk* is
341 equivalent to passing ``lambda x: 0``; in other words, no elements are ignored.
342 For example, pass::
343
344 lambda x: x in " \t"
345
346 if you're comparing lines as sequences of characters, and don't want to synch up
347 on blanks or hard tabs.
348
349 The optional arguments *a* and *b* are sequences to be compared; both default to
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000350 empty strings. The elements of both sequences must be :term:`hashable`.
Georg Brandl116aa622007-08-15 14:28:22 +0000351
Terry Reedy99f96372010-11-25 06:12:34 +0000352 The optional argument *autojunk* can be used to disable the automatic junk
353 heuristic.
354
Benjamin Petersone41251e2008-04-25 01:59:09 +0000355 :class:`SequenceMatcher` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000356
357
Benjamin Petersone41251e2008-04-25 01:59:09 +0000358 .. method:: set_seqs(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000359
Benjamin Petersone41251e2008-04-25 01:59:09 +0000360 Set the two sequences to be compared.
Georg Brandl116aa622007-08-15 14:28:22 +0000361
Benjamin Petersone41251e2008-04-25 01:59:09 +0000362 :class:`SequenceMatcher` computes and caches detailed information about the
363 second sequence, so if you want to compare one sequence against many
364 sequences, use :meth:`set_seq2` to set the commonly used sequence once and
365 call :meth:`set_seq1` repeatedly, once for each of the other sequences.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367
Benjamin Petersone41251e2008-04-25 01:59:09 +0000368 .. method:: set_seq1(a)
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Benjamin Petersone41251e2008-04-25 01:59:09 +0000370 Set the first sequence to be compared. The second sequence to be compared
371 is not changed.
Georg Brandl116aa622007-08-15 14:28:22 +0000372
373
Benjamin Petersone41251e2008-04-25 01:59:09 +0000374 .. method:: set_seq2(b)
Georg Brandl116aa622007-08-15 14:28:22 +0000375
Benjamin Petersone41251e2008-04-25 01:59:09 +0000376 Set the second sequence to be compared. The first sequence to be compared
377 is not changed.
Georg Brandl116aa622007-08-15 14:28:22 +0000378
379
Benjamin Petersone41251e2008-04-25 01:59:09 +0000380 .. method:: find_longest_match(alo, ahi, blo, bhi)
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Benjamin Petersone41251e2008-04-25 01:59:09 +0000382 Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Benjamin Petersone41251e2008-04-25 01:59:09 +0000384 If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
385 ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
386 <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
387 k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
388 <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
389 all maximal matching blocks, return one that starts earliest in *a*, and
390 of all those maximal matching blocks that start earliest in *a*, return
391 the one that starts earliest in *b*.
Georg Brandl116aa622007-08-15 14:28:22 +0000392
Benjamin Petersone41251e2008-04-25 01:59:09 +0000393 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
394 >>> s.find_longest_match(0, 5, 0, 9)
395 Match(a=0, b=4, size=5)
Georg Brandl116aa622007-08-15 14:28:22 +0000396
Benjamin Petersone41251e2008-04-25 01:59:09 +0000397 If *isjunk* was provided, first the longest matching block is determined
398 as above, but with the additional restriction that no junk element appears
399 in the block. Then that block is extended as far as possible by matching
400 (only) junk elements on both sides. So the resulting block never matches
401 on junk except as identical junk happens to be adjacent to an interesting
402 match.
Georg Brandl116aa622007-08-15 14:28:22 +0000403
Benjamin Petersone41251e2008-04-25 01:59:09 +0000404 Here's the same example as before, but considering blanks to be junk. That
405 prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
406 second sequence directly. Instead only the ``'abcd'`` can match, and
407 matches the leftmost ``'abcd'`` in the second sequence:
Georg Brandl116aa622007-08-15 14:28:22 +0000408
Benjamin Petersone41251e2008-04-25 01:59:09 +0000409 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
410 >>> s.find_longest_match(0, 5, 0, 9)
411 Match(a=1, b=0, size=4)
Georg Brandl116aa622007-08-15 14:28:22 +0000412
Benjamin Petersone41251e2008-04-25 01:59:09 +0000413 If no blocks match, this returns ``(alo, blo, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000414
Benjamin Petersone41251e2008-04-25 01:59:09 +0000415 This method returns a :term:`named tuple` ``Match(a, b, size)``.
Christian Heimes25bb7832008-01-11 16:17:00 +0000416
Georg Brandl116aa622007-08-15 14:28:22 +0000417
Benjamin Petersone41251e2008-04-25 01:59:09 +0000418 .. method:: get_matching_blocks()
Georg Brandl116aa622007-08-15 14:28:22 +0000419
Benjamin Petersone41251e2008-04-25 01:59:09 +0000420 Return list of triples describing matching subsequences. Each triple is of
421 the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The
422 triples are monotonically increasing in *i* and *j*.
Georg Brandl116aa622007-08-15 14:28:22 +0000423
Benjamin Petersone41251e2008-04-25 01:59:09 +0000424 The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It
425 is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')``
426 are adjacent triples in the list, and the second is not the last triple in
427 the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
428 triples always describe non-adjacent equal blocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000429
Benjamin Petersone41251e2008-04-25 01:59:09 +0000430 .. XXX Explain why a dummy is used!
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000431
Benjamin Petersone41251e2008-04-25 01:59:09 +0000432 .. doctest::
Georg Brandl116aa622007-08-15 14:28:22 +0000433
Benjamin Petersone41251e2008-04-25 01:59:09 +0000434 >>> s = SequenceMatcher(None, "abxcd", "abcd")
435 >>> s.get_matching_blocks()
436 [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
Georg Brandl116aa622007-08-15 14:28:22 +0000437
438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 .. method:: get_opcodes()
Georg Brandl116aa622007-08-15 14:28:22 +0000440
Benjamin Petersone41251e2008-04-25 01:59:09 +0000441 Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
442 of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 ==
443 0``, and remaining tuples have *i1* equal to the *i2* from the preceding
444 tuple, and, likewise, *j1* equal to the previous *j2*.
Georg Brandl116aa622007-08-15 14:28:22 +0000445
Benjamin Petersone41251e2008-04-25 01:59:09 +0000446 The *tag* values are strings, with these meanings:
Georg Brandl116aa622007-08-15 14:28:22 +0000447
Benjamin Petersone41251e2008-04-25 01:59:09 +0000448 +---------------+---------------------------------------------+
449 | Value | Meaning |
450 +===============+=============================================+
451 | ``'replace'`` | ``a[i1:i2]`` should be replaced by |
452 | | ``b[j1:j2]``. |
453 +---------------+---------------------------------------------+
454 | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that |
455 | | ``j1 == j2`` in this case. |
456 +---------------+---------------------------------------------+
457 | ``'insert'`` | ``b[j1:j2]`` should be inserted at |
458 | | ``a[i1:i1]``. Note that ``i1 == i2`` in |
459 | | this case. |
460 +---------------+---------------------------------------------+
461 | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
462 | | are equal). |
463 +---------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Benjamin Petersone41251e2008-04-25 01:59:09 +0000465 For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000466
Benjamin Petersone41251e2008-04-25 01:59:09 +0000467 >>> a = "qabxcd"
468 >>> b = "abycdf"
469 >>> s = SequenceMatcher(None, a, b)
470 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
471 ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
472 ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))
473 delete a[0:1] (q) b[0:0] ()
474 equal a[1:3] (ab) b[0:2] (ab)
475 replace a[3:4] (x) b[2:3] (y)
476 equal a[4:6] (cd) b[3:5] (cd)
477 insert a[6:6] () b[5:6] (f)
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000480 .. method:: get_grouped_opcodes(n=3)
Georg Brandl116aa622007-08-15 14:28:22 +0000481
Benjamin Petersone41251e2008-04-25 01:59:09 +0000482 Return a :term:`generator` of groups with up to *n* lines of context.
Georg Brandl116aa622007-08-15 14:28:22 +0000483
Benjamin Petersone41251e2008-04-25 01:59:09 +0000484 Starting with the groups returned by :meth:`get_opcodes`, this method
485 splits out smaller change clusters and eliminates intervening ranges which
486 have no changes.
Georg Brandl116aa622007-08-15 14:28:22 +0000487
Benjamin Petersone41251e2008-04-25 01:59:09 +0000488 The groups are returned in the same format as :meth:`get_opcodes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000489
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Benjamin Petersone41251e2008-04-25 01:59:09 +0000491 .. method:: ratio()
Georg Brandl116aa622007-08-15 14:28:22 +0000492
Benjamin Petersone41251e2008-04-25 01:59:09 +0000493 Return a measure of the sequences' similarity as a float in the range [0,
494 1].
Georg Brandl116aa622007-08-15 14:28:22 +0000495
Benjamin Petersone41251e2008-04-25 01:59:09 +0000496 Where T is the total number of elements in both sequences, and M is the
497 number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
498 sequences are identical, and ``0.0`` if they have nothing in common.
Georg Brandl116aa622007-08-15 14:28:22 +0000499
Benjamin Petersone41251e2008-04-25 01:59:09 +0000500 This is expensive to compute if :meth:`get_matching_blocks` or
501 :meth:`get_opcodes` hasn't already been called, in which case you may want
502 to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
503 upper bound.
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505
Benjamin Petersone41251e2008-04-25 01:59:09 +0000506 .. method:: quick_ratio()
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Benjamin Petersone41251e2008-04-25 01:59:09 +0000508 Return an upper bound on :meth:`ratio` relatively quickly.
Georg Brandl116aa622007-08-15 14:28:22 +0000509
Georg Brandl116aa622007-08-15 14:28:22 +0000510
Benjamin Petersone41251e2008-04-25 01:59:09 +0000511 .. method:: real_quick_ratio()
Georg Brandl116aa622007-08-15 14:28:22 +0000512
Benjamin Petersone41251e2008-04-25 01:59:09 +0000513 Return an upper bound on :meth:`ratio` very quickly.
Georg Brandl116aa622007-08-15 14:28:22 +0000514
Georg Brandl116aa622007-08-15 14:28:22 +0000515
516The three methods that return the ratio of matching to total characters can give
517different results due to differing levels of approximation, although
518:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
Christian Heimesfe337bf2008-03-23 21:54:12 +0000519:meth:`ratio`:
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521 >>> s = SequenceMatcher(None, "abcd", "bcde")
522 >>> s.ratio()
523 0.75
524 >>> s.quick_ratio()
525 0.75
526 >>> s.real_quick_ratio()
527 1.0
528
529
530.. _sequencematcher-examples:
531
532SequenceMatcher Examples
533------------------------
534
Christian Heimesfe337bf2008-03-23 21:54:12 +0000535This example compares two strings, considering blanks to be "junk:"
Georg Brandl116aa622007-08-15 14:28:22 +0000536
537 >>> s = SequenceMatcher(lambda x: x == " ",
538 ... "private Thread currentThread;",
539 ... "private volatile Thread currentThread;")
540
541:meth:`ratio` returns a float in [0, 1], measuring the similarity of the
542sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000543sequences are close matches:
Georg Brandl116aa622007-08-15 14:28:22 +0000544
Georg Brandl6911e3c2007-09-04 07:15:32 +0000545 >>> print(round(s.ratio(), 3))
Georg Brandl116aa622007-08-15 14:28:22 +0000546 0.866
547
548If you're only interested in where the sequences match,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000549:meth:`get_matching_blocks` is handy:
Georg Brandl116aa622007-08-15 14:28:22 +0000550
551 >>> for block in s.get_matching_blocks():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000552 ... print("a[%d] and b[%d] match for %d elements" % block)
Georg Brandl116aa622007-08-15 14:28:22 +0000553 a[0] and b[0] match for 8 elements
Christian Heimesfe337bf2008-03-23 21:54:12 +0000554 a[8] and b[17] match for 21 elements
Georg Brandl116aa622007-08-15 14:28:22 +0000555 a[29] and b[38] match for 0 elements
556
557Note that the last tuple returned by :meth:`get_matching_blocks` is always a
558dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
559tuple element (number of elements matched) is ``0``.
560
561If you want to know how to change the first sequence into the second, use
Christian Heimesfe337bf2008-03-23 21:54:12 +0000562:meth:`get_opcodes`:
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564 >>> for opcode in s.get_opcodes():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000565 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Georg Brandl116aa622007-08-15 14:28:22 +0000566 equal a[0:8] b[0:8]
567 insert a[8:8] b[8:17]
Christian Heimesfe337bf2008-03-23 21:54:12 +0000568 equal a[8:29] b[17:38]
Georg Brandl116aa622007-08-15 14:28:22 +0000569
Raymond Hettinger58c8c262009-04-27 21:01:21 +0000570.. seealso::
571
572 * The :func:`get_close_matches` function in this module which shows how
573 simple code building on :class:`SequenceMatcher` can be used to do useful
574 work.
575
576 * `Simple version control recipe
577 <http://code.activestate.com/recipes/576729/>`_ for a small application
578 built with :class:`SequenceMatcher`.
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580
581.. _differ-objects:
582
583Differ Objects
584--------------
585
586Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
587diffs. To the contrary, minimal diffs are often counter-intuitive, because they
588synch up anywhere possible, sometimes accidental matches 100 pages apart.
589Restricting synch points to contiguous matches preserves some notion of
590locality, at the occasional cost of producing a longer diff.
591
592The :class:`Differ` class has this constructor:
593
594
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000595.. class:: Differ(linejunk=None, charjunk=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000596
597 Optional keyword parameters *linejunk* and *charjunk* are for filter functions
598 (or ``None``):
599
600 *linejunk*: A function that accepts a single string argument, and returns true
601 if the string is junk. The default is ``None``, meaning that no line is
602 considered junk.
603
604 *charjunk*: A function that accepts a single character argument (a string of
605 length 1), and returns true if the character is junk. The default is ``None``,
606 meaning that no character is considered junk.
607
Benjamin Petersone41251e2008-04-25 01:59:09 +0000608 :class:`Differ` objects are used (deltas generated) via a single method:
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610
Benjamin Petersone41251e2008-04-25 01:59:09 +0000611 .. method:: Differ.compare(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000612
Benjamin Petersone41251e2008-04-25 01:59:09 +0000613 Compare two sequences of lines, and generate the delta (a sequence of lines).
Georg Brandl116aa622007-08-15 14:28:22 +0000614
Benjamin Petersone41251e2008-04-25 01:59:09 +0000615 Each sequence must contain individual single-line strings ending with newlines.
616 Such sequences can be obtained from the :meth:`readlines` method of file-like
617 objects. The delta generated also consists of newline-terminated strings, ready
618 to be printed as-is via the :meth:`writelines` method of a file-like object.
Georg Brandl116aa622007-08-15 14:28:22 +0000619
620
621.. _differ-examples:
622
623Differ Example
624--------------
625
626This example compares two texts. First we set up the texts, sequences of
627individual single-line strings ending with newlines (such sequences can also be
Christian Heimesfe337bf2008-03-23 21:54:12 +0000628obtained from the :meth:`readlines` method of file-like objects):
Georg Brandl116aa622007-08-15 14:28:22 +0000629
630 >>> text1 = ''' 1. Beautiful is better than ugly.
631 ... 2. Explicit is better than implicit.
632 ... 3. Simple is better than complex.
633 ... 4. Complex is better than complicated.
634 ... '''.splitlines(1)
635 >>> len(text1)
636 4
637 >>> text1[0][-1]
638 '\n'
639 >>> text2 = ''' 1. Beautiful is better than ugly.
640 ... 3. Simple is better than complex.
641 ... 4. Complicated is better than complex.
642 ... 5. Flat is better than nested.
643 ... '''.splitlines(1)
644
Christian Heimesfe337bf2008-03-23 21:54:12 +0000645Next we instantiate a Differ object:
Georg Brandl116aa622007-08-15 14:28:22 +0000646
647 >>> d = Differ()
648
649Note that when instantiating a :class:`Differ` object we may pass functions to
650filter out line and character "junk." See the :meth:`Differ` constructor for
651details.
652
Christian Heimesfe337bf2008-03-23 21:54:12 +0000653Finally, we compare the two:
Georg Brandl116aa622007-08-15 14:28:22 +0000654
655 >>> result = list(d.compare(text1, text2))
656
Christian Heimesfe337bf2008-03-23 21:54:12 +0000657``result`` is a list of strings, so let's pretty-print it:
Georg Brandl116aa622007-08-15 14:28:22 +0000658
659 >>> from pprint import pprint
660 >>> pprint(result)
661 [' 1. Beautiful is better than ugly.\n',
662 '- 2. Explicit is better than implicit.\n',
663 '- 3. Simple is better than complex.\n',
664 '+ 3. Simple is better than complex.\n',
Christian Heimesfe337bf2008-03-23 21:54:12 +0000665 '? ++\n',
Georg Brandl116aa622007-08-15 14:28:22 +0000666 '- 4. Complex is better than complicated.\n',
Christian Heimesfe337bf2008-03-23 21:54:12 +0000667 '? ^ ---- ^\n',
Georg Brandl116aa622007-08-15 14:28:22 +0000668 '+ 4. Complicated is better than complex.\n',
Christian Heimesfe337bf2008-03-23 21:54:12 +0000669 '? ++++ ^ ^\n',
Georg Brandl116aa622007-08-15 14:28:22 +0000670 '+ 5. Flat is better than nested.\n']
671
Christian Heimesfe337bf2008-03-23 21:54:12 +0000672As a single multi-line string it looks like this:
Georg Brandl116aa622007-08-15 14:28:22 +0000673
674 >>> import sys
675 >>> sys.stdout.writelines(result)
676 1. Beautiful is better than ugly.
677 - 2. Explicit is better than implicit.
678 - 3. Simple is better than complex.
679 + 3. Simple is better than complex.
680 ? ++
681 - 4. Complex is better than complicated.
682 ? ^ ---- ^
683 + 4. Complicated is better than complex.
684 ? ++++ ^ ^
685 + 5. Flat is better than nested.
686
Christian Heimes8640e742008-02-23 16:23:06 +0000687
688.. _difflib-interface:
689
690A command-line interface to difflib
691-----------------------------------
692
693This example shows how to use difflib to create a ``diff``-like utility.
694It is also contained in the Python source distribution, as
695:file:`Tools/scripts/diff.py`.
696
Christian Heimesfe337bf2008-03-23 21:54:12 +0000697.. testcode::
Christian Heimes8640e742008-02-23 16:23:06 +0000698
699 """ Command line interface to difflib.py providing diffs in four formats:
700
701 * ndiff: lists every line and highlights interline changes.
702 * context: highlights clusters of changes in a before/after format.
703 * unified: highlights clusters of changes in an inline format.
704 * html: generates side by side comparison with change highlights.
705
706 """
707
708 import sys, os, time, difflib, optparse
709
710 def main():
711 # Configure the option parser
712 usage = "usage: %prog [options] fromfile tofile"
713 parser = optparse.OptionParser(usage)
714 parser.add_option("-c", action="store_true", default=False,
715 help='Produce a context format diff (default)')
716 parser.add_option("-u", action="store_true", default=False,
717 help='Produce a unified format diff')
718 hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)'
719 parser.add_option("-m", action="store_true", default=False, help=hlp)
720 parser.add_option("-n", action="store_true", default=False,
721 help='Produce a ndiff format diff')
722 parser.add_option("-l", "--lines", type="int", default=3,
723 help='Set number of context lines (default 3)')
724 (options, args) = parser.parse_args()
725
726 if len(args) == 0:
727 parser.print_help()
728 sys.exit(1)
729 if len(args) != 2:
730 parser.error("need to specify both a fromfile and tofile")
731
732 n = options.lines
733 fromfile, tofile = args # as specified in the usage string
734
735 # we're passing these as arguments to the diff function
736 fromdate = time.ctime(os.stat(fromfile).st_mtime)
737 todate = time.ctime(os.stat(tofile).st_mtime)
738 fromlines = open(fromfile, 'U').readlines()
739 tolines = open(tofile, 'U').readlines()
740
741 if options.u:
742 diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,
743 fromdate, todate, n=n)
744 elif options.n:
745 diff = difflib.ndiff(fromlines, tolines)
746 elif options.m:
747 diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
748 tofile, context=options.c,
749 numlines=n)
750 else:
751 diff = difflib.context_diff(fromlines, tolines, fromfile, tofile,
752 fromdate, todate, n=n)
753
754 # we're using writelines because diff is a generator
755 sys.stdout.writelines(diff)
756
757 if __name__ == '__main__':
758 main()