blob: 442706556e0765e9385372aef48e5e9d7d6199d5 [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
Andrew Kuchling2e3743c2014-03-19 16:23:01 -040010**Source code:** :source:`Lib/difflib.py`
11
Christian Heimesfe337bf2008-03-23 21:54:12 +000012.. testsetup::
Georg Brandl116aa622007-08-15 14:28:22 +000013
Christian Heimesfe337bf2008-03-23 21:54:12 +000014 import sys
15 from difflib import *
Georg Brandl116aa622007-08-15 14:28:22 +000016
Georg Brandl9afde1c2007-11-01 20:32:30 +000017This module provides classes and functions for comparing sequences. It
18can be used for example, for comparing files, and can produce difference
19information in various formats, including HTML and context and unified
20diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
21
Terry Reedy99f96372010-11-25 06:12:34 +000022
Georg Brandl116aa622007-08-15 14:28:22 +000023.. class:: SequenceMatcher
24
25 This is a flexible class for comparing pairs of sequences of any type, so long
Guido van Rossum2cc30da2007-11-02 23:46:40 +000026 as the sequence elements are :term:`hashable`. The basic algorithm predates, and is a
Georg Brandl116aa622007-08-15 14:28:22 +000027 little fancier than, an algorithm published in the late 1980's by Ratcliff and
28 Obershelp under the hyperbolic name "gestalt pattern matching." The idea is to
29 find the longest contiguous matching subsequence that contains no "junk"
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -040030 elements; these "junk" elements are ones that are uninteresting in some
31 sense, such as blank lines or whitespace. (Handling junk is an
32 extension to the Ratcliff and Obershelp algorithm.) The same
Georg Brandl116aa622007-08-15 14:28:22 +000033 idea is then applied recursively to the pieces of the sequences to the left and
34 to the right of the matching subsequence. This does not yield minimal edit
35 sequences, but does tend to yield matches that "look right" to people.
36
37 **Timing:** The basic Ratcliff-Obershelp algorithm is cubic time in the worst
38 case and quadratic time in the expected case. :class:`SequenceMatcher` is
39 quadratic time for the worst case and has expected-case behavior dependent in a
40 complicated way on how many elements the sequences have in common; best case
41 time is linear.
42
Terry Reedy99f96372010-11-25 06:12:34 +000043 **Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic that
44 automatically treats certain sequence items as junk. The heuristic counts how many
45 times each individual item appears in the sequence. If an item's duplicates (after
46 the first one) account for more than 1% of the sequence and the sequence is at least
47 200 items long, this item is marked as "popular" and is treated as junk for
48 the purpose of sequence matching. This heuristic can be turned off by setting
49 the ``autojunk`` argument to ``False`` when creating the :class:`SequenceMatcher`.
50
Terry Reedydc9b17d2010-11-27 20:52:14 +000051 .. versionadded:: 3.2
52 The *autojunk* parameter.
53
Georg Brandl116aa622007-08-15 14:28:22 +000054
55.. class:: Differ
56
57 This is a class for comparing sequences of lines of text, and producing
58 human-readable differences or deltas. Differ uses :class:`SequenceMatcher`
59 both to compare sequences of lines, and to compare sequences of characters
60 within similar (near-matching) lines.
61
62 Each line of a :class:`Differ` delta begins with a two-letter code:
63
64 +----------+-------------------------------------------+
65 | Code | Meaning |
66 +==========+===========================================+
67 | ``'- '`` | line unique to sequence 1 |
68 +----------+-------------------------------------------+
69 | ``'+ '`` | line unique to sequence 2 |
70 +----------+-------------------------------------------+
71 | ``' '`` | line common to both sequences |
72 +----------+-------------------------------------------+
73 | ``'? '`` | line not present in either input sequence |
74 +----------+-------------------------------------------+
75
76 Lines beginning with '``?``' attempt to guide the eye to intraline differences,
77 and were not present in either input sequence. These lines can be confusing if
78 the sequences contain tab characters.
79
80
81.. class:: HtmlDiff
82
83 This class can be used to create an HTML table (or a complete HTML file
84 containing the table) showing a side by side, line by line comparison of text
85 with inter-line and intra-line change highlights. The table can be generated in
86 either full or contextual difference mode.
87
88 The constructor for this class is:
89
90
Georg Brandlc2a4f4f2009-04-10 09:03:43 +000091 .. method:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK)
Georg Brandl116aa622007-08-15 14:28:22 +000092
93 Initializes instance of :class:`HtmlDiff`.
94
95 *tabsize* is an optional keyword argument to specify tab stop spacing and
96 defaults to ``8``.
97
98 *wrapcolumn* is an optional keyword to specify column number where lines are
99 broken and wrapped, defaults to ``None`` where lines are not wrapped.
100
101 *linejunk* and *charjunk* are optional keyword arguments passed into ``ndiff()``
102 (used by :class:`HtmlDiff` to generate the side by side HTML differences). See
103 ``ndiff()`` documentation for argument default values and descriptions.
104
105 The following methods are public:
106
Berker Peksag102029d2015-03-15 01:18:47 +0200107 .. method:: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, \
108 numlines=5, *, charset='utf-8')
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110 Compares *fromlines* and *tolines* (lists of strings) and returns a string which
111 is a complete HTML file containing a table showing line by line differences with
112 inter-line and intra-line changes highlighted.
113
114 *fromdesc* and *todesc* are optional keyword arguments to specify from/to file
115 column header strings (both default to an empty string).
116
117 *context* and *numlines* are both optional keyword arguments. Set *context* to
118 ``True`` when contextual differences are to be shown, else the default is
119 ``False`` to show the full files. *numlines* defaults to ``5``. When *context*
120 is ``True`` *numlines* controls the number of context lines which surround the
121 difference highlights. When *context* is ``False`` *numlines* controls the
122 number of lines which are shown before a difference highlight when using the
123 "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place
124 the next difference highlight at the top of the browser without any leading
125 context).
126
Berker Peksag102029d2015-03-15 01:18:47 +0200127 .. versionchanged:: 3.5
128 *charset* keyword-only argument was added. The default charset of
129 HTML document changed from ``'ISO-8859-1'`` to ``'utf-8'``.
130
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000131 .. method:: make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5)
Georg Brandl116aa622007-08-15 14:28:22 +0000132
133 Compares *fromlines* and *tolines* (lists of strings) and returns a string which
134 is a complete HTML table showing line by line differences with inter-line and
135 intra-line changes highlighted.
136
137 The arguments for this method are the same as those for the :meth:`make_file`
138 method.
139
140 :file:`Tools/scripts/diff.py` is a command-line front-end to this class and
141 contains a good example of its use.
142
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000144.. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Georg Brandl9afde1c2007-11-01 20:32:30 +0000146 Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
147 generating the delta lines) in context diff format.
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 Context diffs are a compact way of showing just the lines that have changed plus
150 a few lines of context. The changes are shown in a before/after style. The
151 number of context lines is set by *n* which defaults to three.
152
153 By default, the diff control lines (those with ``***`` or ``---``) are created
154 with a trailing newline. This is helpful so that inputs created from
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300155 :func:`io.IOBase.readlines` result in diffs that are suitable for use with
156 :func:`io.IOBase.writelines` since both the inputs and outputs have trailing
Georg Brandl116aa622007-08-15 14:28:22 +0000157 newlines.
158
159 For inputs that do not have trailing newlines, set the *lineterm* argument to
160 ``""`` so that the output will be uniformly newline free.
161
162 The context diff format normally has a header for filenames and modification
163 times. Any or all of these may be specified using strings for *fromfile*,
R. David Murrayb2416e52010-04-12 16:58:02 +0000164 *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
165 expressed in the ISO 8601 format. If not specified, the
Georg Brandl116aa622007-08-15 14:28:22 +0000166 strings default to blanks.
167
Christian Heimes8640e742008-02-23 16:23:06 +0000168 >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
169 >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
170 >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'):
Christian Heimesfe337bf2008-03-23 21:54:12 +0000171 ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
Christian Heimes8640e742008-02-23 16:23:06 +0000172 *** before.py
173 --- after.py
174 ***************
175 *** 1,4 ****
176 ! bacon
177 ! eggs
178 ! ham
179 guido
180 --- 1,4 ----
181 ! python
182 ! eggy
183 ! hamster
184 guido
185
186 See :ref:`difflib-interface` for a more detailed example.
Georg Brandl116aa622007-08-15 14:28:22 +0000187
Georg Brandl116aa622007-08-15 14:28:22 +0000188
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000189.. function:: get_close_matches(word, possibilities, n=3, cutoff=0.6)
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191 Return a list of the best "good enough" matches. *word* is a sequence for which
192 close matches are desired (typically a string), and *possibilities* is a list of
193 sequences against which to match *word* (typically a list of strings).
194
195 Optional argument *n* (default ``3``) is the maximum number of close matches to
196 return; *n* must be greater than ``0``.
197
198 Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1].
199 Possibilities that don't score at least that similar to *word* are ignored.
200
201 The best (no more than *n*) matches among the possibilities are returned in a
Christian Heimesfe337bf2008-03-23 21:54:12 +0000202 list, sorted by similarity score, most similar first.
Georg Brandl116aa622007-08-15 14:28:22 +0000203
204 >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy'])
205 ['apple', 'ape']
206 >>> import keyword
207 >>> get_close_matches('wheel', keyword.kwlist)
208 ['while']
209 >>> get_close_matches('apple', keyword.kwlist)
210 []
211 >>> get_close_matches('accept', keyword.kwlist)
212 ['except']
213
214
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000215.. function:: ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK)
Georg Brandl116aa622007-08-15 14:28:22 +0000216
Georg Brandl9afde1c2007-11-01 20:32:30 +0000217 Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style
218 delta (a :term:`generator` generating the delta lines).
Georg Brandl116aa622007-08-15 14:28:22 +0000219
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -0400220 Optional keyword parameters *linejunk* and *charjunk* are filtering functions
Georg Brandl116aa622007-08-15 14:28:22 +0000221 (or ``None``):
222
Georg Brandle6bcc912008-05-12 18:05:20 +0000223 *linejunk*: A function that accepts a single string argument, and returns
224 true if the string is junk, or false if not. The default is ``None``. There
225 is also a module-level function :func:`IS_LINE_JUNK`, which filters out lines
226 without visible characters, except for at most one pound character (``'#'``)
227 -- however the underlying :class:`SequenceMatcher` class does a dynamic
228 analysis of which lines are so frequent as to constitute noise, and this
229 usually works better than using this function.
Georg Brandl116aa622007-08-15 14:28:22 +0000230
231 *charjunk*: A function that accepts a character (a string of length 1), and
232 returns if the character is junk, or false if not. The default is module-level
233 function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -0400234 blank or tab; it's a bad idea to include newline in this!).
Georg Brandl116aa622007-08-15 14:28:22 +0000235
Christian Heimesfe337bf2008-03-23 21:54:12 +0000236 :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function.
Georg Brandl116aa622007-08-15 14:28:22 +0000237
Terry Jan Reedybddecc32014-04-18 17:00:19 -0400238 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
239 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Georg Brandl6911e3c2007-09-04 07:15:32 +0000240 >>> print(''.join(diff), end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000241 - one
242 ? ^
243 + ore
244 ? ^
245 - two
246 - three
247 ? -
248 + tree
249 + emu
250
251
252.. function:: restore(sequence, which)
253
254 Return one of the two sequences that generated a delta.
255
256 Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract
257 lines originating from file 1 or 2 (parameter *which*), stripping off line
258 prefixes.
259
Christian Heimesfe337bf2008-03-23 21:54:12 +0000260 Example:
Georg Brandl116aa622007-08-15 14:28:22 +0000261
Terry Jan Reedybddecc32014-04-18 17:00:19 -0400262 >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(keepends=True),
263 ... 'ore\ntree\nemu\n'.splitlines(keepends=True))
Georg Brandl116aa622007-08-15 14:28:22 +0000264 >>> diff = list(diff) # materialize the generated delta into a list
Georg Brandl6911e3c2007-09-04 07:15:32 +0000265 >>> print(''.join(restore(diff, 1)), end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000266 one
267 two
268 three
Georg Brandl6911e3c2007-09-04 07:15:32 +0000269 >>> print(''.join(restore(diff, 2)), end="")
Georg Brandl116aa622007-08-15 14:28:22 +0000270 ore
271 tree
272 emu
273
274
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000275.. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n')
Georg Brandl116aa622007-08-15 14:28:22 +0000276
Georg Brandl9afde1c2007-11-01 20:32:30 +0000277 Compare *a* and *b* (lists of strings); return a delta (a :term:`generator`
278 generating the delta lines) in unified diff format.
Georg Brandl116aa622007-08-15 14:28:22 +0000279
280 Unified diffs are a compact way of showing just the lines that have changed plus
281 a few lines of context. The changes are shown in a inline style (instead of
282 separate before/after blocks). The number of context lines is set by *n* which
283 defaults to three.
284
285 By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are
286 created with a trailing newline. This is helpful so that inputs created from
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300287 :func:`io.IOBase.readlines` result in diffs that are suitable for use with
288 :func:`io.IOBase.writelines` since both the inputs and outputs have trailing
Georg Brandl116aa622007-08-15 14:28:22 +0000289 newlines.
290
291 For inputs that do not have trailing newlines, set the *lineterm* argument to
292 ``""`` so that the output will be uniformly newline free.
293
294 The context diff format normally has a header for filenames and modification
295 times. Any or all of these may be specified using strings for *fromfile*,
R. David Murrayb2416e52010-04-12 16:58:02 +0000296 *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally
297 expressed in the ISO 8601 format. If not specified, the
Georg Brandl116aa622007-08-15 14:28:22 +0000298 strings default to blanks.
299
Christian Heimes8640e742008-02-23 16:23:06 +0000300
301 >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n']
302 >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n']
303 >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'):
Christian Heimesfe337bf2008-03-23 21:54:12 +0000304 ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE
Christian Heimes8640e742008-02-23 16:23:06 +0000305 --- before.py
306 +++ after.py
307 @@ -1,4 +1,4 @@
308 -bacon
309 -eggs
310 -ham
311 +python
312 +eggy
313 +hamster
314 guido
315
316 See :ref:`difflib-interface` for a more detailed example.
Georg Brandl116aa622007-08-15 14:28:22 +0000317
Georg Brandl116aa622007-08-15 14:28:22 +0000318
319.. function:: IS_LINE_JUNK(line)
320
321 Return true for ignorable lines. The line *line* is ignorable if *line* is
322 blank or contains a single ``'#'``, otherwise it is not ignorable. Used as a
Georg Brandle6bcc912008-05-12 18:05:20 +0000323 default for parameter *linejunk* in :func:`ndiff` in older versions.
Georg Brandl116aa622007-08-15 14:28:22 +0000324
325
326.. function:: IS_CHARACTER_JUNK(ch)
327
328 Return true for ignorable characters. The character *ch* is ignorable if *ch*
329 is a space or tab, otherwise it is not ignorable. Used as a default for
330 parameter *charjunk* in :func:`ndiff`.
331
332
333.. seealso::
334
Georg Brandl525d3552014-10-29 10:26:56 +0100335 `Pattern Matching: The Gestalt Approach <http://www.drdobbs.com/database/pattern-matching-the-gestalt-approach/184407970>`_
Georg Brandl116aa622007-08-15 14:28:22 +0000336 Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This
Georg Brandl525d3552014-10-29 10:26:56 +0100337 was published in `Dr. Dobb's Journal <http://www.drdobbs.com/>`_ in July, 1988.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
339
340.. _sequence-matcher:
341
342SequenceMatcher Objects
343-----------------------
344
345The :class:`SequenceMatcher` class has this constructor:
346
347
Terry Reedy99f96372010-11-25 06:12:34 +0000348.. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350 Optional argument *isjunk* must be ``None`` (the default) or a one-argument
351 function that takes a sequence element and returns true if and only if the
352 element is "junk" and should be ignored. Passing ``None`` for *isjunk* is
353 equivalent to passing ``lambda x: 0``; in other words, no elements are ignored.
354 For example, pass::
355
356 lambda x: x in " \t"
357
358 if you're comparing lines as sequences of characters, and don't want to synch up
359 on blanks or hard tabs.
360
361 The optional arguments *a* and *b* are sequences to be compared; both default to
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000362 empty strings. The elements of both sequences must be :term:`hashable`.
Georg Brandl116aa622007-08-15 14:28:22 +0000363
Terry Reedy99f96372010-11-25 06:12:34 +0000364 The optional argument *autojunk* can be used to disable the automatic junk
365 heuristic.
366
Terry Reedydc9b17d2010-11-27 20:52:14 +0000367 .. versionadded:: 3.2
368 The *autojunk* parameter.
369
Terry Reedy74a7c672010-12-03 18:57:42 +0000370 SequenceMatcher objects get three data attributes: *bjunk* is the
Serhiy Storchakafbc1c262013-11-29 12:17:13 +0200371 set of elements of *b* for which *isjunk* is ``True``; *bpopular* is the set of
Terry Reedy17a59252010-12-15 20:18:10 +0000372 non-junk elements considered popular by the heuristic (if it is not
373 disabled); *b2j* is a dict mapping the remaining elements of *b* to a list
374 of positions where they occur. All three are reset whenever *b* is reset
375 with :meth:`set_seqs` or :meth:`set_seq2`.
Terry Reedy74a7c672010-12-03 18:57:42 +0000376
Georg Brandl500be242010-12-03 19:56:42 +0000377 .. versionadded:: 3.2
Terry Reedy74a7c672010-12-03 18:57:42 +0000378 The *bjunk* and *bpopular* attributes.
379
Benjamin Petersone41251e2008-04-25 01:59:09 +0000380 :class:`SequenceMatcher` objects have the following methods:
Georg Brandl116aa622007-08-15 14:28:22 +0000381
Benjamin Petersone41251e2008-04-25 01:59:09 +0000382 .. method:: set_seqs(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000383
Benjamin Petersone41251e2008-04-25 01:59:09 +0000384 Set the two sequences to be compared.
Georg Brandl116aa622007-08-15 14:28:22 +0000385
Benjamin Petersone41251e2008-04-25 01:59:09 +0000386 :class:`SequenceMatcher` computes and caches detailed information about the
387 second sequence, so if you want to compare one sequence against many
388 sequences, use :meth:`set_seq2` to set the commonly used sequence once and
389 call :meth:`set_seq1` repeatedly, once for each of the other sequences.
Georg Brandl116aa622007-08-15 14:28:22 +0000390
391
Benjamin Petersone41251e2008-04-25 01:59:09 +0000392 .. method:: set_seq1(a)
Georg Brandl116aa622007-08-15 14:28:22 +0000393
Benjamin Petersone41251e2008-04-25 01:59:09 +0000394 Set the first sequence to be compared. The second sequence to be compared
395 is not changed.
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397
Benjamin Petersone41251e2008-04-25 01:59:09 +0000398 .. method:: set_seq2(b)
Georg Brandl116aa622007-08-15 14:28:22 +0000399
Benjamin Petersone41251e2008-04-25 01:59:09 +0000400 Set the second sequence to be compared. The first sequence to be compared
401 is not changed.
Georg Brandl116aa622007-08-15 14:28:22 +0000402
403
Benjamin Petersone41251e2008-04-25 01:59:09 +0000404 .. method:: find_longest_match(alo, ahi, blo, bhi)
Georg Brandl116aa622007-08-15 14:28:22 +0000405
Benjamin Petersone41251e2008-04-25 01:59:09 +0000406 Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
Benjamin Petersone41251e2008-04-25 01:59:09 +0000408 If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns
409 ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo
410 <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j',
411 k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i
412 <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of
413 all maximal matching blocks, return one that starts earliest in *a*, and
414 of all those maximal matching blocks that start earliest in *a*, return
415 the one that starts earliest in *b*.
Georg Brandl116aa622007-08-15 14:28:22 +0000416
Benjamin Petersone41251e2008-04-25 01:59:09 +0000417 >>> s = SequenceMatcher(None, " abcd", "abcd abcd")
418 >>> s.find_longest_match(0, 5, 0, 9)
419 Match(a=0, b=4, size=5)
Georg Brandl116aa622007-08-15 14:28:22 +0000420
Benjamin Petersone41251e2008-04-25 01:59:09 +0000421 If *isjunk* was provided, first the longest matching block is determined
422 as above, but with the additional restriction that no junk element appears
423 in the block. Then that block is extended as far as possible by matching
424 (only) junk elements on both sides. So the resulting block never matches
425 on junk except as identical junk happens to be adjacent to an interesting
426 match.
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Benjamin Petersone41251e2008-04-25 01:59:09 +0000428 Here's the same example as before, but considering blanks to be junk. That
429 prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the
430 second sequence directly. Instead only the ``'abcd'`` can match, and
431 matches the leftmost ``'abcd'`` in the second sequence:
Georg Brandl116aa622007-08-15 14:28:22 +0000432
Benjamin Petersone41251e2008-04-25 01:59:09 +0000433 >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
434 >>> s.find_longest_match(0, 5, 0, 9)
435 Match(a=1, b=0, size=4)
Georg Brandl116aa622007-08-15 14:28:22 +0000436
Benjamin Petersone41251e2008-04-25 01:59:09 +0000437 If no blocks match, this returns ``(alo, blo, 0)``.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
Benjamin Petersone41251e2008-04-25 01:59:09 +0000439 This method returns a :term:`named tuple` ``Match(a, b, size)``.
Christian Heimes25bb7832008-01-11 16:17:00 +0000440
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Benjamin Petersone41251e2008-04-25 01:59:09 +0000442 .. method:: get_matching_blocks()
Georg Brandl116aa622007-08-15 14:28:22 +0000443
Benjamin Petersone41251e2008-04-25 01:59:09 +0000444 Return list of triples describing matching subsequences. Each triple is of
445 the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The
446 triples are monotonically increasing in *i* and *j*.
Georg Brandl116aa622007-08-15 14:28:22 +0000447
Benjamin Petersone41251e2008-04-25 01:59:09 +0000448 The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It
449 is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')``
450 are adjacent triples in the list, and the second is not the last triple in
451 the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent
452 triples always describe non-adjacent equal blocks.
Georg Brandl116aa622007-08-15 14:28:22 +0000453
Benjamin Petersone41251e2008-04-25 01:59:09 +0000454 .. XXX Explain why a dummy is used!
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000455
Benjamin Petersone41251e2008-04-25 01:59:09 +0000456 .. doctest::
Georg Brandl116aa622007-08-15 14:28:22 +0000457
Benjamin Petersone41251e2008-04-25 01:59:09 +0000458 >>> s = SequenceMatcher(None, "abxcd", "abcd")
459 >>> s.get_matching_blocks()
460 [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 +0000461
462
Benjamin Petersone41251e2008-04-25 01:59:09 +0000463 .. method:: get_opcodes()
Georg Brandl116aa622007-08-15 14:28:22 +0000464
Benjamin Petersone41251e2008-04-25 01:59:09 +0000465 Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is
466 of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 ==
467 0``, and remaining tuples have *i1* equal to the *i2* from the preceding
468 tuple, and, likewise, *j1* equal to the previous *j2*.
Georg Brandl116aa622007-08-15 14:28:22 +0000469
Benjamin Petersone41251e2008-04-25 01:59:09 +0000470 The *tag* values are strings, with these meanings:
Georg Brandl116aa622007-08-15 14:28:22 +0000471
Benjamin Petersone41251e2008-04-25 01:59:09 +0000472 +---------------+---------------------------------------------+
473 | Value | Meaning |
474 +===============+=============================================+
475 | ``'replace'`` | ``a[i1:i2]`` should be replaced by |
476 | | ``b[j1:j2]``. |
477 +---------------+---------------------------------------------+
478 | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that |
479 | | ``j1 == j2`` in this case. |
480 +---------------+---------------------------------------------+
481 | ``'insert'`` | ``b[j1:j2]`` should be inserted at |
482 | | ``a[i1:i1]``. Note that ``i1 == i2`` in |
483 | | this case. |
484 +---------------+---------------------------------------------+
485 | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences |
486 | | are equal). |
487 +---------------+---------------------------------------------+
Georg Brandl116aa622007-08-15 14:28:22 +0000488
Benjamin Petersone41251e2008-04-25 01:59:09 +0000489 For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000490
Benjamin Petersone41251e2008-04-25 01:59:09 +0000491 >>> a = "qabxcd"
492 >>> b = "abycdf"
493 >>> s = SequenceMatcher(None, a, b)
494 >>> for tag, i1, i2, j1, j2 in s.get_opcodes():
Raymond Hettingerdbb677a2011-04-09 19:41:00 -0700495 print('{:7} a[{}:{}] --> b[{}:{}] {!r:>8} --> {!r}'.format(
496 tag, i1, i2, j1, j2, a[i1:i2], b[j1:j2]))
497
498
499 delete a[0:1] --> b[0:0] 'q' --> ''
500 equal a[1:3] --> b[0:2] 'ab' --> 'ab'
501 replace a[3:4] --> b[2:3] 'x' --> 'y'
502 equal a[4:6] --> b[3:5] 'cd' --> 'cd'
503 insert a[6:6] --> b[5:6] '' --> 'f'
Georg Brandl116aa622007-08-15 14:28:22 +0000504
505
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000506 .. method:: get_grouped_opcodes(n=3)
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Benjamin Petersone41251e2008-04-25 01:59:09 +0000508 Return a :term:`generator` of groups with up to *n* lines of context.
Georg Brandl116aa622007-08-15 14:28:22 +0000509
Benjamin Petersone41251e2008-04-25 01:59:09 +0000510 Starting with the groups returned by :meth:`get_opcodes`, this method
511 splits out smaller change clusters and eliminates intervening ranges which
512 have no changes.
Georg Brandl116aa622007-08-15 14:28:22 +0000513
Benjamin Petersone41251e2008-04-25 01:59:09 +0000514 The groups are returned in the same format as :meth:`get_opcodes`.
Georg Brandl116aa622007-08-15 14:28:22 +0000515
Georg Brandl116aa622007-08-15 14:28:22 +0000516
Benjamin Petersone41251e2008-04-25 01:59:09 +0000517 .. method:: ratio()
Georg Brandl116aa622007-08-15 14:28:22 +0000518
Benjamin Petersone41251e2008-04-25 01:59:09 +0000519 Return a measure of the sequences' similarity as a float in the range [0,
520 1].
Georg Brandl116aa622007-08-15 14:28:22 +0000521
Benjamin Petersone41251e2008-04-25 01:59:09 +0000522 Where T is the total number of elements in both sequences, and M is the
523 number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the
524 sequences are identical, and ``0.0`` if they have nothing in common.
Georg Brandl116aa622007-08-15 14:28:22 +0000525
Benjamin Petersone41251e2008-04-25 01:59:09 +0000526 This is expensive to compute if :meth:`get_matching_blocks` or
527 :meth:`get_opcodes` hasn't already been called, in which case you may want
528 to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an
529 upper bound.
Georg Brandl116aa622007-08-15 14:28:22 +0000530
531
Benjamin Petersone41251e2008-04-25 01:59:09 +0000532 .. method:: quick_ratio()
Georg Brandl116aa622007-08-15 14:28:22 +0000533
Benjamin Petersone41251e2008-04-25 01:59:09 +0000534 Return an upper bound on :meth:`ratio` relatively quickly.
Georg Brandl116aa622007-08-15 14:28:22 +0000535
Georg Brandl116aa622007-08-15 14:28:22 +0000536
Benjamin Petersone41251e2008-04-25 01:59:09 +0000537 .. method:: real_quick_ratio()
Georg Brandl116aa622007-08-15 14:28:22 +0000538
Benjamin Petersone41251e2008-04-25 01:59:09 +0000539 Return an upper bound on :meth:`ratio` very quickly.
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Georg Brandl116aa622007-08-15 14:28:22 +0000541
542The three methods that return the ratio of matching to total characters can give
543different results due to differing levels of approximation, although
544:meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as
Christian Heimesfe337bf2008-03-23 21:54:12 +0000545:meth:`ratio`:
Georg Brandl116aa622007-08-15 14:28:22 +0000546
547 >>> s = SequenceMatcher(None, "abcd", "bcde")
548 >>> s.ratio()
549 0.75
550 >>> s.quick_ratio()
551 0.75
552 >>> s.real_quick_ratio()
553 1.0
554
555
556.. _sequencematcher-examples:
557
558SequenceMatcher Examples
559------------------------
560
Terry Reedy74a7c672010-12-03 18:57:42 +0000561This example compares two strings, considering blanks to be "junk":
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563 >>> s = SequenceMatcher(lambda x: x == " ",
564 ... "private Thread currentThread;",
565 ... "private volatile Thread currentThread;")
566
567:meth:`ratio` returns a float in [0, 1], measuring the similarity of the
568sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the
Christian Heimesfe337bf2008-03-23 21:54:12 +0000569sequences are close matches:
Georg Brandl116aa622007-08-15 14:28:22 +0000570
Georg Brandl6911e3c2007-09-04 07:15:32 +0000571 >>> print(round(s.ratio(), 3))
Georg Brandl116aa622007-08-15 14:28:22 +0000572 0.866
573
574If you're only interested in where the sequences match,
Christian Heimesfe337bf2008-03-23 21:54:12 +0000575:meth:`get_matching_blocks` is handy:
Georg Brandl116aa622007-08-15 14:28:22 +0000576
577 >>> for block in s.get_matching_blocks():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000578 ... print("a[%d] and b[%d] match for %d elements" % block)
Georg Brandl116aa622007-08-15 14:28:22 +0000579 a[0] and b[0] match for 8 elements
Christian Heimesfe337bf2008-03-23 21:54:12 +0000580 a[8] and b[17] match for 21 elements
Georg Brandl116aa622007-08-15 14:28:22 +0000581 a[29] and b[38] match for 0 elements
582
583Note that the last tuple returned by :meth:`get_matching_blocks` is always a
584dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last
585tuple element (number of elements matched) is ``0``.
586
587If you want to know how to change the first sequence into the second, use
Christian Heimesfe337bf2008-03-23 21:54:12 +0000588:meth:`get_opcodes`:
Georg Brandl116aa622007-08-15 14:28:22 +0000589
590 >>> for opcode in s.get_opcodes():
Georg Brandl6911e3c2007-09-04 07:15:32 +0000591 ... print("%6s a[%d:%d] b[%d:%d]" % opcode)
Georg Brandl116aa622007-08-15 14:28:22 +0000592 equal a[0:8] b[0:8]
593 insert a[8:8] b[8:17]
Christian Heimesfe337bf2008-03-23 21:54:12 +0000594 equal a[8:29] b[17:38]
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Raymond Hettinger58c8c262009-04-27 21:01:21 +0000596.. seealso::
597
598 * The :func:`get_close_matches` function in this module which shows how
599 simple code building on :class:`SequenceMatcher` can be used to do useful
600 work.
601
602 * `Simple version control recipe
603 <http://code.activestate.com/recipes/576729/>`_ for a small application
604 built with :class:`SequenceMatcher`.
Georg Brandl116aa622007-08-15 14:28:22 +0000605
606
607.. _differ-objects:
608
609Differ Objects
610--------------
611
612Note that :class:`Differ`\ -generated deltas make no claim to be **minimal**
613diffs. To the contrary, minimal diffs are often counter-intuitive, because they
614synch up anywhere possible, sometimes accidental matches 100 pages apart.
615Restricting synch points to contiguous matches preserves some notion of
616locality, at the occasional cost of producing a longer diff.
617
618The :class:`Differ` class has this constructor:
619
620
Georg Brandlc2a4f4f2009-04-10 09:03:43 +0000621.. class:: Differ(linejunk=None, charjunk=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000622
623 Optional keyword parameters *linejunk* and *charjunk* are for filter functions
624 (or ``None``):
625
626 *linejunk*: A function that accepts a single string argument, and returns true
627 if the string is junk. The default is ``None``, meaning that no line is
628 considered junk.
629
630 *charjunk*: A function that accepts a single character argument (a string of
631 length 1), and returns true if the character is junk. The default is ``None``,
632 meaning that no character is considered junk.
633
Andrew Kuchlingc51da2b2014-03-19 16:43:06 -0400634 These junk-filtering functions speed up matching to find
635 differences and do not cause any differing lines or characters to
636 be ignored. Read the description of the
637 :meth:`~SequenceMatcher.find_longest_match` method's *isjunk*
638 parameter for an explanation.
639
Benjamin Petersone41251e2008-04-25 01:59:09 +0000640 :class:`Differ` objects are used (deltas generated) via a single method:
Georg Brandl116aa622007-08-15 14:28:22 +0000641
642
Benjamin Petersone41251e2008-04-25 01:59:09 +0000643 .. method:: Differ.compare(a, b)
Georg Brandl116aa622007-08-15 14:28:22 +0000644
Benjamin Petersone41251e2008-04-25 01:59:09 +0000645 Compare two sequences of lines, and generate the delta (a sequence of lines).
Georg Brandl116aa622007-08-15 14:28:22 +0000646
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300647 Each sequence must contain individual single-line strings ending with
648 newlines. Such sequences can be obtained from the
649 :meth:`~io.IOBase.readlines` method of file-like objects. The delta
650 generated also consists of newline-terminated strings, ready to be
651 printed as-is via the :meth:`~io.IOBase.writelines` method of a
652 file-like object.
Georg Brandl116aa622007-08-15 14:28:22 +0000653
654
655.. _differ-examples:
656
657Differ Example
658--------------
659
660This example compares two texts. First we set up the texts, sequences of
661individual single-line strings ending with newlines (such sequences can also be
Serhiy Storchakabfdcd432013-10-13 23:09:14 +0300662obtained from the :meth:`~io.BaseIO.readlines` method of file-like objects):
Georg Brandl116aa622007-08-15 14:28:22 +0000663
664 >>> text1 = ''' 1. Beautiful is better than ugly.
665 ... 2. Explicit is better than implicit.
666 ... 3. Simple is better than complex.
667 ... 4. Complex is better than complicated.
Terry Jan Reedybddecc32014-04-18 17:00:19 -0400668 ... '''.splitlines(keepends=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000669 >>> len(text1)
670 4
671 >>> text1[0][-1]
672 '\n'
673 >>> text2 = ''' 1. Beautiful is better than ugly.
674 ... 3. Simple is better than complex.
675 ... 4. Complicated is better than complex.
676 ... 5. Flat is better than nested.
Terry Jan Reedybddecc32014-04-18 17:00:19 -0400677 ... '''.splitlines(keepends=True)
Georg Brandl116aa622007-08-15 14:28:22 +0000678
Christian Heimesfe337bf2008-03-23 21:54:12 +0000679Next we instantiate a Differ object:
Georg Brandl116aa622007-08-15 14:28:22 +0000680
681 >>> d = Differ()
682
683Note that when instantiating a :class:`Differ` object we may pass functions to
684filter out line and character "junk." See the :meth:`Differ` constructor for
685details.
686
Christian Heimesfe337bf2008-03-23 21:54:12 +0000687Finally, we compare the two:
Georg Brandl116aa622007-08-15 14:28:22 +0000688
689 >>> result = list(d.compare(text1, text2))
690
Christian Heimesfe337bf2008-03-23 21:54:12 +0000691``result`` is a list of strings, so let's pretty-print it:
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693 >>> from pprint import pprint
694 >>> pprint(result)
695 [' 1. Beautiful is better than ugly.\n',
696 '- 2. Explicit is better than implicit.\n',
697 '- 3. Simple is better than complex.\n',
698 '+ 3. Simple is better than complex.\n',
Christian Heimesfe337bf2008-03-23 21:54:12 +0000699 '? ++\n',
Georg Brandl116aa622007-08-15 14:28:22 +0000700 '- 4. Complex is better than complicated.\n',
Christian Heimesfe337bf2008-03-23 21:54:12 +0000701 '? ^ ---- ^\n',
Georg Brandl116aa622007-08-15 14:28:22 +0000702 '+ 4. Complicated is better than complex.\n',
Christian Heimesfe337bf2008-03-23 21:54:12 +0000703 '? ++++ ^ ^\n',
Georg Brandl116aa622007-08-15 14:28:22 +0000704 '+ 5. Flat is better than nested.\n']
705
Christian Heimesfe337bf2008-03-23 21:54:12 +0000706As a single multi-line string it looks like this:
Georg Brandl116aa622007-08-15 14:28:22 +0000707
708 >>> import sys
709 >>> sys.stdout.writelines(result)
710 1. Beautiful is better than ugly.
711 - 2. Explicit is better than implicit.
712 - 3. Simple is better than complex.
713 + 3. Simple is better than complex.
714 ? ++
715 - 4. Complex is better than complicated.
716 ? ^ ---- ^
717 + 4. Complicated is better than complex.
718 ? ++++ ^ ^
719 + 5. Flat is better than nested.
720
Christian Heimes8640e742008-02-23 16:23:06 +0000721
722.. _difflib-interface:
723
724A command-line interface to difflib
725-----------------------------------
726
727This example shows how to use difflib to create a ``diff``-like utility.
728It is also contained in the Python source distribution, as
729:file:`Tools/scripts/diff.py`.
730
Christian Heimesfe337bf2008-03-23 21:54:12 +0000731.. testcode::
Christian Heimes8640e742008-02-23 16:23:06 +0000732
733 """ Command line interface to difflib.py providing diffs in four formats:
734
735 * ndiff: lists every line and highlights interline changes.
736 * context: highlights clusters of changes in a before/after format.
737 * unified: highlights clusters of changes in an inline format.
738 * html: generates side by side comparison with change highlights.
739
740 """
741
742 import sys, os, time, difflib, optparse
743
744 def main():
745 # Configure the option parser
746 usage = "usage: %prog [options] fromfile tofile"
747 parser = optparse.OptionParser(usage)
748 parser.add_option("-c", action="store_true", default=False,
749 help='Produce a context format diff (default)')
750 parser.add_option("-u", action="store_true", default=False,
751 help='Produce a unified format diff')
752 hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)'
753 parser.add_option("-m", action="store_true", default=False, help=hlp)
754 parser.add_option("-n", action="store_true", default=False,
755 help='Produce a ndiff format diff')
756 parser.add_option("-l", "--lines", type="int", default=3,
757 help='Set number of context lines (default 3)')
758 (options, args) = parser.parse_args()
759
760 if len(args) == 0:
761 parser.print_help()
762 sys.exit(1)
763 if len(args) != 2:
764 parser.error("need to specify both a fromfile and tofile")
765
766 n = options.lines
767 fromfile, tofile = args # as specified in the usage string
768
769 # we're passing these as arguments to the diff function
770 fromdate = time.ctime(os.stat(fromfile).st_mtime)
771 todate = time.ctime(os.stat(tofile).st_mtime)
R David Murray96433f82013-07-30 15:37:11 -0400772 with open(fromfile) as fromf, open(tofile) as tof:
Éric Araujoa3dd56b2011-03-11 17:42:48 +0100773 fromlines, tolines = list(fromf), list(tof)
Christian Heimes8640e742008-02-23 16:23:06 +0000774
775 if options.u:
776 diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile,
777 fromdate, todate, n=n)
778 elif options.n:
779 diff = difflib.ndiff(fromlines, tolines)
780 elif options.m:
781 diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile,
782 tofile, context=options.c,
783 numlines=n)
784 else:
785 diff = difflib.context_diff(fromlines, tolines, fromfile, tofile,
786 fromdate, todate, n=n)
787
788 # we're using writelines because diff is a generator
789 sys.stdout.writelines(diff)
790
791 if __name__ == '__main__':
792 main()