Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | :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 Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 8 | .. Markup by Fred L. Drake, Jr. <fdrake@acm.org> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 10 | .. testsetup:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 12 | import sys |
| 13 | from difflib import * |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 14 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 15 | This module provides classes and functions for comparing sequences. It |
| 16 | can be used for example, for comparing files, and can produce difference |
| 17 | information in various formats, including HTML and context and unified |
| 18 | diffs. For comparing directories and files, see also, the :mod:`filecmp` module. |
| 19 | |
Terry Reedy | 99f9637 | 2010-11-25 06:12:34 +0000 | [diff] [blame] | 20 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 | .. class:: SequenceMatcher |
| 22 | |
| 23 | This is a flexible class for comparing pairs of sequences of any type, so long |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 24 | as the sequence elements are :term:`hashable`. The basic algorithm predates, and is a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 25 | 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 Reedy | 99f9637 | 2010-11-25 06:12:34 +0000 | [diff] [blame] | 39 | **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 | |
Terry Reedy | dc9b17d | 2010-11-27 20:52:14 +0000 | [diff] [blame] | 47 | .. versionadded:: 3.2 |
| 48 | The *autojunk* parameter. |
| 49 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 50 | |
| 51 | .. class:: Differ |
| 52 | |
| 53 | This is a class for comparing sequences of lines of text, and producing |
| 54 | human-readable differences or deltas. Differ uses :class:`SequenceMatcher` |
| 55 | both to compare sequences of lines, and to compare sequences of characters |
| 56 | within similar (near-matching) lines. |
| 57 | |
| 58 | Each line of a :class:`Differ` delta begins with a two-letter code: |
| 59 | |
| 60 | +----------+-------------------------------------------+ |
| 61 | | Code | Meaning | |
| 62 | +==========+===========================================+ |
| 63 | | ``'- '`` | line unique to sequence 1 | |
| 64 | +----------+-------------------------------------------+ |
| 65 | | ``'+ '`` | line unique to sequence 2 | |
| 66 | +----------+-------------------------------------------+ |
| 67 | | ``' '`` | line common to both sequences | |
| 68 | +----------+-------------------------------------------+ |
| 69 | | ``'? '`` | line not present in either input sequence | |
| 70 | +----------+-------------------------------------------+ |
| 71 | |
| 72 | Lines beginning with '``?``' attempt to guide the eye to intraline differences, |
| 73 | and were not present in either input sequence. These lines can be confusing if |
| 74 | the sequences contain tab characters. |
| 75 | |
| 76 | |
| 77 | .. class:: HtmlDiff |
| 78 | |
| 79 | This class can be used to create an HTML table (or a complete HTML file |
| 80 | containing the table) showing a side by side, line by line comparison of text |
| 81 | with inter-line and intra-line change highlights. The table can be generated in |
| 82 | either full or contextual difference mode. |
| 83 | |
| 84 | The constructor for this class is: |
| 85 | |
| 86 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 87 | .. method:: __init__(tabsize=8, wrapcolumn=None, linejunk=None, charjunk=IS_CHARACTER_JUNK) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 88 | |
| 89 | Initializes instance of :class:`HtmlDiff`. |
| 90 | |
| 91 | *tabsize* is an optional keyword argument to specify tab stop spacing and |
| 92 | defaults to ``8``. |
| 93 | |
| 94 | *wrapcolumn* is an optional keyword to specify column number where lines are |
| 95 | broken and wrapped, defaults to ``None`` where lines are not wrapped. |
| 96 | |
| 97 | *linejunk* and *charjunk* are optional keyword arguments passed into ``ndiff()`` |
| 98 | (used by :class:`HtmlDiff` to generate the side by side HTML differences). See |
| 99 | ``ndiff()`` documentation for argument default values and descriptions. |
| 100 | |
| 101 | The following methods are public: |
| 102 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 103 | .. method:: make_file(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 104 | |
| 105 | Compares *fromlines* and *tolines* (lists of strings) and returns a string which |
| 106 | is a complete HTML file containing a table showing line by line differences with |
| 107 | inter-line and intra-line changes highlighted. |
| 108 | |
| 109 | *fromdesc* and *todesc* are optional keyword arguments to specify from/to file |
| 110 | column header strings (both default to an empty string). |
| 111 | |
| 112 | *context* and *numlines* are both optional keyword arguments. Set *context* to |
| 113 | ``True`` when contextual differences are to be shown, else the default is |
| 114 | ``False`` to show the full files. *numlines* defaults to ``5``. When *context* |
| 115 | is ``True`` *numlines* controls the number of context lines which surround the |
| 116 | difference highlights. When *context* is ``False`` *numlines* controls the |
| 117 | number of lines which are shown before a difference highlight when using the |
| 118 | "next" hyperlinks (setting to zero would cause the "next" hyperlinks to place |
| 119 | the next difference highlight at the top of the browser without any leading |
| 120 | context). |
| 121 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 122 | .. method:: make_table(fromlines, tolines, fromdesc='', todesc='', context=False, numlines=5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 123 | |
| 124 | Compares *fromlines* and *tolines* (lists of strings) and returns a string which |
| 125 | is a complete HTML table showing line by line differences with inter-line and |
| 126 | intra-line changes highlighted. |
| 127 | |
| 128 | The arguments for this method are the same as those for the :meth:`make_file` |
| 129 | method. |
| 130 | |
| 131 | :file:`Tools/scripts/diff.py` is a command-line front-end to this class and |
| 132 | contains a good example of its use. |
| 133 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 134 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 135 | .. function:: context_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 136 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 137 | Compare *a* and *b* (lists of strings); return a delta (a :term:`generator` |
| 138 | generating the delta lines) in context diff format. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | |
| 140 | Context diffs are a compact way of showing just the lines that have changed plus |
| 141 | a few lines of context. The changes are shown in a before/after style. The |
| 142 | number of context lines is set by *n* which defaults to three. |
| 143 | |
| 144 | By default, the diff control lines (those with ``***`` or ``---``) are created |
| 145 | with a trailing newline. This is helpful so that inputs created from |
| 146 | :func:`file.readlines` result in diffs that are suitable for use with |
| 147 | :func:`file.writelines` since both the inputs and outputs have trailing |
| 148 | newlines. |
| 149 | |
| 150 | For inputs that do not have trailing newlines, set the *lineterm* argument to |
| 151 | ``""`` so that the output will be uniformly newline free. |
| 152 | |
| 153 | The context diff format normally has a header for filenames and modification |
| 154 | times. Any or all of these may be specified using strings for *fromfile*, |
R. David Murray | b2416e5 | 2010-04-12 16:58:02 +0000 | [diff] [blame] | 155 | *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally |
| 156 | expressed in the ISO 8601 format. If not specified, the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | strings default to blanks. |
| 158 | |
Christian Heimes | 8640e74 | 2008-02-23 16:23:06 +0000 | [diff] [blame] | 159 | >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] |
| 160 | >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] |
| 161 | >>> for line in context_diff(s1, s2, fromfile='before.py', tofile='after.py'): |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 162 | ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE |
Christian Heimes | 8640e74 | 2008-02-23 16:23:06 +0000 | [diff] [blame] | 163 | *** before.py |
| 164 | --- after.py |
| 165 | *************** |
| 166 | *** 1,4 **** |
| 167 | ! bacon |
| 168 | ! eggs |
| 169 | ! ham |
| 170 | guido |
| 171 | --- 1,4 ---- |
| 172 | ! python |
| 173 | ! eggy |
| 174 | ! hamster |
| 175 | guido |
| 176 | |
| 177 | See :ref:`difflib-interface` for a more detailed example. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 178 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 179 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 180 | .. function:: get_close_matches(word, possibilities, n=3, cutoff=0.6) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | |
| 182 | Return a list of the best "good enough" matches. *word* is a sequence for which |
| 183 | close matches are desired (typically a string), and *possibilities* is a list of |
| 184 | sequences against which to match *word* (typically a list of strings). |
| 185 | |
| 186 | Optional argument *n* (default ``3``) is the maximum number of close matches to |
| 187 | return; *n* must be greater than ``0``. |
| 188 | |
| 189 | Optional argument *cutoff* (default ``0.6``) is a float in the range [0, 1]. |
| 190 | Possibilities that don't score at least that similar to *word* are ignored. |
| 191 | |
| 192 | The best (no more than *n*) matches among the possibilities are returned in a |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 193 | list, sorted by similarity score, most similar first. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | |
| 195 | >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) |
| 196 | ['apple', 'ape'] |
| 197 | >>> import keyword |
| 198 | >>> get_close_matches('wheel', keyword.kwlist) |
| 199 | ['while'] |
| 200 | >>> get_close_matches('apple', keyword.kwlist) |
| 201 | [] |
| 202 | >>> get_close_matches('accept', keyword.kwlist) |
| 203 | ['except'] |
| 204 | |
| 205 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 206 | .. function:: ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 207 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 208 | Compare *a* and *b* (lists of strings); return a :class:`Differ`\ -style |
| 209 | delta (a :term:`generator` generating the delta lines). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | |
| 211 | Optional keyword parameters *linejunk* and *charjunk* are for filter functions |
| 212 | (or ``None``): |
| 213 | |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 214 | *linejunk*: A function that accepts a single string argument, and returns |
| 215 | true if the string is junk, or false if not. The default is ``None``. There |
| 216 | is also a module-level function :func:`IS_LINE_JUNK`, which filters out lines |
| 217 | without visible characters, except for at most one pound character (``'#'``) |
| 218 | -- however the underlying :class:`SequenceMatcher` class does a dynamic |
| 219 | analysis of which lines are so frequent as to constitute noise, and this |
| 220 | usually works better than using this function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 221 | |
| 222 | *charjunk*: A function that accepts a character (a string of length 1), and |
| 223 | returns if the character is junk, or false if not. The default is module-level |
| 224 | function :func:`IS_CHARACTER_JUNK`, which filters out whitespace characters (a |
| 225 | blank or tab; note: bad idea to include newline in this!). |
| 226 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 227 | :file:`Tools/scripts/ndiff.py` is a command-line front-end to this function. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 228 | |
| 229 | >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), |
| 230 | ... 'ore\ntree\nemu\n'.splitlines(1)) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 231 | >>> print(''.join(diff), end="") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 232 | - one |
| 233 | ? ^ |
| 234 | + ore |
| 235 | ? ^ |
| 236 | - two |
| 237 | - three |
| 238 | ? - |
| 239 | + tree |
| 240 | + emu |
| 241 | |
| 242 | |
| 243 | .. function:: restore(sequence, which) |
| 244 | |
| 245 | Return one of the two sequences that generated a delta. |
| 246 | |
| 247 | Given a *sequence* produced by :meth:`Differ.compare` or :func:`ndiff`, extract |
| 248 | lines originating from file 1 or 2 (parameter *which*), stripping off line |
| 249 | prefixes. |
| 250 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 251 | Example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 252 | |
| 253 | >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), |
| 254 | ... 'ore\ntree\nemu\n'.splitlines(1)) |
| 255 | >>> diff = list(diff) # materialize the generated delta into a list |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 256 | >>> print(''.join(restore(diff, 1)), end="") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 257 | one |
| 258 | two |
| 259 | three |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 260 | >>> print(''.join(restore(diff, 2)), end="") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 261 | ore |
| 262 | tree |
| 263 | emu |
| 264 | |
| 265 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 266 | .. function:: unified_diff(a, b, fromfile='', tofile='', fromfiledate='', tofiledate='', n=3, lineterm='\\n') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 267 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 268 | Compare *a* and *b* (lists of strings); return a delta (a :term:`generator` |
| 269 | generating the delta lines) in unified diff format. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 270 | |
| 271 | Unified diffs are a compact way of showing just the lines that have changed plus |
| 272 | a few lines of context. The changes are shown in a inline style (instead of |
| 273 | separate before/after blocks). The number of context lines is set by *n* which |
| 274 | defaults to three. |
| 275 | |
| 276 | By default, the diff control lines (those with ``---``, ``+++``, or ``@@``) are |
| 277 | created with a trailing newline. This is helpful so that inputs created from |
| 278 | :func:`file.readlines` result in diffs that are suitable for use with |
| 279 | :func:`file.writelines` since both the inputs and outputs have trailing |
| 280 | newlines. |
| 281 | |
| 282 | For inputs that do not have trailing newlines, set the *lineterm* argument to |
| 283 | ``""`` so that the output will be uniformly newline free. |
| 284 | |
| 285 | The context diff format normally has a header for filenames and modification |
| 286 | times. Any or all of these may be specified using strings for *fromfile*, |
R. David Murray | b2416e5 | 2010-04-12 16:58:02 +0000 | [diff] [blame] | 287 | *tofile*, *fromfiledate*, and *tofiledate*. The modification times are normally |
| 288 | expressed in the ISO 8601 format. If not specified, the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 289 | strings default to blanks. |
| 290 | |
Christian Heimes | 8640e74 | 2008-02-23 16:23:06 +0000 | [diff] [blame] | 291 | |
| 292 | >>> s1 = ['bacon\n', 'eggs\n', 'ham\n', 'guido\n'] |
| 293 | >>> s2 = ['python\n', 'eggy\n', 'hamster\n', 'guido\n'] |
| 294 | >>> for line in unified_diff(s1, s2, fromfile='before.py', tofile='after.py'): |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 295 | ... sys.stdout.write(line) # doctest: +NORMALIZE_WHITESPACE |
Christian Heimes | 8640e74 | 2008-02-23 16:23:06 +0000 | [diff] [blame] | 296 | --- before.py |
| 297 | +++ after.py |
| 298 | @@ -1,4 +1,4 @@ |
| 299 | -bacon |
| 300 | -eggs |
| 301 | -ham |
| 302 | +python |
| 303 | +eggy |
| 304 | +hamster |
| 305 | guido |
| 306 | |
| 307 | See :ref:`difflib-interface` for a more detailed example. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 308 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 309 | |
| 310 | .. function:: IS_LINE_JUNK(line) |
| 311 | |
| 312 | Return true for ignorable lines. The line *line* is ignorable if *line* is |
| 313 | blank or contains a single ``'#'``, otherwise it is not ignorable. Used as a |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 314 | default for parameter *linejunk* in :func:`ndiff` in older versions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 315 | |
| 316 | |
| 317 | .. function:: IS_CHARACTER_JUNK(ch) |
| 318 | |
| 319 | Return true for ignorable characters. The character *ch* is ignorable if *ch* |
| 320 | is a space or tab, otherwise it is not ignorable. Used as a default for |
| 321 | parameter *charjunk* in :func:`ndiff`. |
| 322 | |
| 323 | |
| 324 | .. seealso:: |
| 325 | |
| 326 | `Pattern Matching: The Gestalt Approach <http://www.ddj.com/184407970?pgno=5>`_ |
| 327 | Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This |
| 328 | was published in `Dr. Dobb's Journal <http://www.ddj.com/>`_ in July, 1988. |
| 329 | |
| 330 | |
| 331 | .. _sequence-matcher: |
| 332 | |
| 333 | SequenceMatcher Objects |
| 334 | ----------------------- |
| 335 | |
| 336 | The :class:`SequenceMatcher` class has this constructor: |
| 337 | |
| 338 | |
Terry Reedy | 99f9637 | 2010-11-25 06:12:34 +0000 | [diff] [blame] | 339 | .. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 340 | |
| 341 | Optional argument *isjunk* must be ``None`` (the default) or a one-argument |
| 342 | function that takes a sequence element and returns true if and only if the |
| 343 | element is "junk" and should be ignored. Passing ``None`` for *isjunk* is |
| 344 | equivalent to passing ``lambda x: 0``; in other words, no elements are ignored. |
| 345 | For example, pass:: |
| 346 | |
| 347 | lambda x: x in " \t" |
| 348 | |
| 349 | if you're comparing lines as sequences of characters, and don't want to synch up |
| 350 | on blanks or hard tabs. |
| 351 | |
| 352 | The optional arguments *a* and *b* are sequences to be compared; both default to |
Guido van Rossum | 2cc30da | 2007-11-02 23:46:40 +0000 | [diff] [blame] | 353 | empty strings. The elements of both sequences must be :term:`hashable`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 354 | |
Terry Reedy | 99f9637 | 2010-11-25 06:12:34 +0000 | [diff] [blame] | 355 | The optional argument *autojunk* can be used to disable the automatic junk |
| 356 | heuristic. |
| 357 | |
Terry Reedy | dc9b17d | 2010-11-27 20:52:14 +0000 | [diff] [blame] | 358 | .. versionadded:: 3.2 |
| 359 | The *autojunk* parameter. |
| 360 | |
Terry Reedy | 74a7c67 | 2010-12-03 18:57:42 +0000 | [diff] [blame] | 361 | SequenceMatcher objects get three data attributes: *bjunk* is the |
Terry Reedy | 17a5925 | 2010-12-15 20:18:10 +0000 | [diff] [blame] | 362 | set of elements of *b* for which *isjunk* is True; *bpopular* is the set of |
| 363 | non-junk elements considered popular by the heuristic (if it is not |
| 364 | disabled); *b2j* is a dict mapping the remaining elements of *b* to a list |
| 365 | of positions where they occur. All three are reset whenever *b* is reset |
| 366 | with :meth:`set_seqs` or :meth:`set_seq2`. |
Terry Reedy | 74a7c67 | 2010-12-03 18:57:42 +0000 | [diff] [blame] | 367 | |
Georg Brandl | 500be24 | 2010-12-03 19:56:42 +0000 | [diff] [blame] | 368 | .. versionadded:: 3.2 |
Terry Reedy | 74a7c67 | 2010-12-03 18:57:42 +0000 | [diff] [blame] | 369 | The *bjunk* and *bpopular* attributes. |
| 370 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 371 | :class:`SequenceMatcher` objects have the following methods: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 372 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 373 | .. method:: set_seqs(a, b) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 374 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 375 | Set the two sequences to be compared. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 376 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 377 | :class:`SequenceMatcher` computes and caches detailed information about the |
| 378 | second sequence, so if you want to compare one sequence against many |
| 379 | sequences, use :meth:`set_seq2` to set the commonly used sequence once and |
| 380 | call :meth:`set_seq1` repeatedly, once for each of the other sequences. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | |
| 382 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 383 | .. method:: set_seq1(a) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 384 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 385 | Set the first sequence to be compared. The second sequence to be compared |
| 386 | is not changed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 387 | |
| 388 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 389 | .. method:: set_seq2(b) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 390 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 391 | Set the second sequence to be compared. The first sequence to be compared |
| 392 | is not changed. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 393 | |
| 394 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 395 | .. method:: find_longest_match(alo, ahi, blo, bhi) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 396 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 397 | Find longest matching block in ``a[alo:ahi]`` and ``b[blo:bhi]``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 398 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 399 | If *isjunk* was omitted or ``None``, :meth:`find_longest_match` returns |
| 400 | ``(i, j, k)`` such that ``a[i:i+k]`` is equal to ``b[j:j+k]``, where ``alo |
| 401 | <= i <= i+k <= ahi`` and ``blo <= j <= j+k <= bhi``. For all ``(i', j', |
| 402 | k')`` meeting those conditions, the additional conditions ``k >= k'``, ``i |
| 403 | <= i'``, and if ``i == i'``, ``j <= j'`` are also met. In other words, of |
| 404 | all maximal matching blocks, return one that starts earliest in *a*, and |
| 405 | of all those maximal matching blocks that start earliest in *a*, return |
| 406 | the one that starts earliest in *b*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 407 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 408 | >>> s = SequenceMatcher(None, " abcd", "abcd abcd") |
| 409 | >>> s.find_longest_match(0, 5, 0, 9) |
| 410 | Match(a=0, b=4, size=5) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 411 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 412 | If *isjunk* was provided, first the longest matching block is determined |
| 413 | as above, but with the additional restriction that no junk element appears |
| 414 | in the block. Then that block is extended as far as possible by matching |
| 415 | (only) junk elements on both sides. So the resulting block never matches |
| 416 | on junk except as identical junk happens to be adjacent to an interesting |
| 417 | match. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 418 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 419 | Here's the same example as before, but considering blanks to be junk. That |
| 420 | prevents ``' abcd'`` from matching the ``' abcd'`` at the tail end of the |
| 421 | second sequence directly. Instead only the ``'abcd'`` can match, and |
| 422 | matches the leftmost ``'abcd'`` in the second sequence: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 423 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 424 | >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") |
| 425 | >>> s.find_longest_match(0, 5, 0, 9) |
| 426 | Match(a=1, b=0, size=4) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 427 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 428 | If no blocks match, this returns ``(alo, blo, 0)``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 429 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 430 | This method returns a :term:`named tuple` ``Match(a, b, size)``. |
Christian Heimes | 25bb783 | 2008-01-11 16:17:00 +0000 | [diff] [blame] | 431 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 433 | .. method:: get_matching_blocks() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 434 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 435 | Return list of triples describing matching subsequences. Each triple is of |
| 436 | the form ``(i, j, n)``, and means that ``a[i:i+n] == b[j:j+n]``. The |
| 437 | triples are monotonically increasing in *i* and *j*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 438 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 439 | The last triple is a dummy, and has the value ``(len(a), len(b), 0)``. It |
| 440 | is the only triple with ``n == 0``. If ``(i, j, n)`` and ``(i', j', n')`` |
| 441 | are adjacent triples in the list, and the second is not the last triple in |
| 442 | the list, then ``i+n != i'`` or ``j+n != j'``; in other words, adjacent |
| 443 | triples always describe non-adjacent equal blocks. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 444 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 445 | .. XXX Explain why a dummy is used! |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 446 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 447 | .. doctest:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 448 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 449 | >>> s = SequenceMatcher(None, "abxcd", "abcd") |
| 450 | >>> s.get_matching_blocks() |
| 451 | [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 452 | |
| 453 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 454 | .. method:: get_opcodes() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 455 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 456 | Return list of 5-tuples describing how to turn *a* into *b*. Each tuple is |
| 457 | of the form ``(tag, i1, i2, j1, j2)``. The first tuple has ``i1 == j1 == |
| 458 | 0``, and remaining tuples have *i1* equal to the *i2* from the preceding |
| 459 | tuple, and, likewise, *j1* equal to the previous *j2*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 460 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 461 | The *tag* values are strings, with these meanings: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 462 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 463 | +---------------+---------------------------------------------+ |
| 464 | | Value | Meaning | |
| 465 | +===============+=============================================+ |
| 466 | | ``'replace'`` | ``a[i1:i2]`` should be replaced by | |
| 467 | | | ``b[j1:j2]``. | |
| 468 | +---------------+---------------------------------------------+ |
| 469 | | ``'delete'`` | ``a[i1:i2]`` should be deleted. Note that | |
| 470 | | | ``j1 == j2`` in this case. | |
| 471 | +---------------+---------------------------------------------+ |
| 472 | | ``'insert'`` | ``b[j1:j2]`` should be inserted at | |
| 473 | | | ``a[i1:i1]``. Note that ``i1 == i2`` in | |
| 474 | | | this case. | |
| 475 | +---------------+---------------------------------------------+ |
| 476 | | ``'equal'`` | ``a[i1:i2] == b[j1:j2]`` (the sub-sequences | |
| 477 | | | are equal). | |
| 478 | +---------------+---------------------------------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 479 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 480 | For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 481 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 482 | >>> a = "qabxcd" |
| 483 | >>> b = "abycdf" |
| 484 | >>> s = SequenceMatcher(None, a, b) |
| 485 | >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): |
| 486 | ... print(("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % |
| 487 | ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))) |
| 488 | delete a[0:1] (q) b[0:0] () |
| 489 | equal a[1:3] (ab) b[0:2] (ab) |
| 490 | replace a[3:4] (x) b[2:3] (y) |
| 491 | equal a[4:6] (cd) b[3:5] (cd) |
| 492 | insert a[6:6] () b[5:6] (f) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 493 | |
| 494 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 495 | .. method:: get_grouped_opcodes(n=3) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 496 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 497 | Return a :term:`generator` of groups with up to *n* lines of context. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 498 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 499 | Starting with the groups returned by :meth:`get_opcodes`, this method |
| 500 | splits out smaller change clusters and eliminates intervening ranges which |
| 501 | have no changes. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 502 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 503 | The groups are returned in the same format as :meth:`get_opcodes`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 504 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 505 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 506 | .. method:: ratio() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 507 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 508 | Return a measure of the sequences' similarity as a float in the range [0, |
| 509 | 1]. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 510 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 511 | Where T is the total number of elements in both sequences, and M is the |
| 512 | number of matches, this is 2.0\*M / T. Note that this is ``1.0`` if the |
| 513 | sequences are identical, and ``0.0`` if they have nothing in common. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 514 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 515 | This is expensive to compute if :meth:`get_matching_blocks` or |
| 516 | :meth:`get_opcodes` hasn't already been called, in which case you may want |
| 517 | to try :meth:`quick_ratio` or :meth:`real_quick_ratio` first to get an |
| 518 | upper bound. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 519 | |
| 520 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 521 | .. method:: quick_ratio() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 522 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 523 | Return an upper bound on :meth:`ratio` relatively quickly. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 524 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 525 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 526 | .. method:: real_quick_ratio() |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 527 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 528 | Return an upper bound on :meth:`ratio` very quickly. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 529 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 530 | |
| 531 | The three methods that return the ratio of matching to total characters can give |
| 532 | different results due to differing levels of approximation, although |
| 533 | :meth:`quick_ratio` and :meth:`real_quick_ratio` are always at least as large as |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 534 | :meth:`ratio`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 535 | |
| 536 | >>> s = SequenceMatcher(None, "abcd", "bcde") |
| 537 | >>> s.ratio() |
| 538 | 0.75 |
| 539 | >>> s.quick_ratio() |
| 540 | 0.75 |
| 541 | >>> s.real_quick_ratio() |
| 542 | 1.0 |
| 543 | |
| 544 | |
| 545 | .. _sequencematcher-examples: |
| 546 | |
| 547 | SequenceMatcher Examples |
| 548 | ------------------------ |
| 549 | |
Terry Reedy | 74a7c67 | 2010-12-03 18:57:42 +0000 | [diff] [blame] | 550 | This example compares two strings, considering blanks to be "junk": |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 551 | |
| 552 | >>> s = SequenceMatcher(lambda x: x == " ", |
| 553 | ... "private Thread currentThread;", |
| 554 | ... "private volatile Thread currentThread;") |
| 555 | |
| 556 | :meth:`ratio` returns a float in [0, 1], measuring the similarity of the |
| 557 | sequences. As a rule of thumb, a :meth:`ratio` value over 0.6 means the |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 558 | sequences are close matches: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 559 | |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 560 | >>> print(round(s.ratio(), 3)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 561 | 0.866 |
| 562 | |
| 563 | If you're only interested in where the sequences match, |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 564 | :meth:`get_matching_blocks` is handy: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 565 | |
| 566 | >>> for block in s.get_matching_blocks(): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 567 | ... print("a[%d] and b[%d] match for %d elements" % block) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 568 | a[0] and b[0] match for 8 elements |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 569 | a[8] and b[17] match for 21 elements |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 570 | a[29] and b[38] match for 0 elements |
| 571 | |
| 572 | Note that the last tuple returned by :meth:`get_matching_blocks` is always a |
| 573 | dummy, ``(len(a), len(b), 0)``, and this is the only case in which the last |
| 574 | tuple element (number of elements matched) is ``0``. |
| 575 | |
| 576 | If you want to know how to change the first sequence into the second, use |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 577 | :meth:`get_opcodes`: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 578 | |
| 579 | >>> for opcode in s.get_opcodes(): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 580 | ... print("%6s a[%d:%d] b[%d:%d]" % opcode) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 581 | equal a[0:8] b[0:8] |
| 582 | insert a[8:8] b[8:17] |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 583 | equal a[8:29] b[17:38] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 584 | |
Raymond Hettinger | 58c8c26 | 2009-04-27 21:01:21 +0000 | [diff] [blame] | 585 | .. seealso:: |
| 586 | |
| 587 | * The :func:`get_close_matches` function in this module which shows how |
| 588 | simple code building on :class:`SequenceMatcher` can be used to do useful |
| 589 | work. |
| 590 | |
| 591 | * `Simple version control recipe |
| 592 | <http://code.activestate.com/recipes/576729/>`_ for a small application |
| 593 | built with :class:`SequenceMatcher`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 594 | |
| 595 | |
| 596 | .. _differ-objects: |
| 597 | |
| 598 | Differ Objects |
| 599 | -------------- |
| 600 | |
| 601 | Note that :class:`Differ`\ -generated deltas make no claim to be **minimal** |
| 602 | diffs. To the contrary, minimal diffs are often counter-intuitive, because they |
| 603 | synch up anywhere possible, sometimes accidental matches 100 pages apart. |
| 604 | Restricting synch points to contiguous matches preserves some notion of |
| 605 | locality, at the occasional cost of producing a longer diff. |
| 606 | |
| 607 | The :class:`Differ` class has this constructor: |
| 608 | |
| 609 | |
Georg Brandl | c2a4f4f | 2009-04-10 09:03:43 +0000 | [diff] [blame] | 610 | .. class:: Differ(linejunk=None, charjunk=None) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 611 | |
| 612 | Optional keyword parameters *linejunk* and *charjunk* are for filter functions |
| 613 | (or ``None``): |
| 614 | |
| 615 | *linejunk*: A function that accepts a single string argument, and returns true |
| 616 | if the string is junk. The default is ``None``, meaning that no line is |
| 617 | considered junk. |
| 618 | |
| 619 | *charjunk*: A function that accepts a single character argument (a string of |
| 620 | length 1), and returns true if the character is junk. The default is ``None``, |
| 621 | meaning that no character is considered junk. |
| 622 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 623 | :class:`Differ` objects are used (deltas generated) via a single method: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 624 | |
| 625 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 626 | .. method:: Differ.compare(a, b) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 627 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 628 | Compare two sequences of lines, and generate the delta (a sequence of lines). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 629 | |
Benjamin Peterson | e41251e | 2008-04-25 01:59:09 +0000 | [diff] [blame] | 630 | Each sequence must contain individual single-line strings ending with newlines. |
| 631 | Such sequences can be obtained from the :meth:`readlines` method of file-like |
| 632 | objects. The delta generated also consists of newline-terminated strings, ready |
| 633 | to be printed as-is via the :meth:`writelines` method of a file-like object. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 634 | |
| 635 | |
| 636 | .. _differ-examples: |
| 637 | |
| 638 | Differ Example |
| 639 | -------------- |
| 640 | |
| 641 | This example compares two texts. First we set up the texts, sequences of |
| 642 | individual single-line strings ending with newlines (such sequences can also be |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 643 | obtained from the :meth:`readlines` method of file-like objects): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 644 | |
| 645 | >>> text1 = ''' 1. Beautiful is better than ugly. |
| 646 | ... 2. Explicit is better than implicit. |
| 647 | ... 3. Simple is better than complex. |
| 648 | ... 4. Complex is better than complicated. |
| 649 | ... '''.splitlines(1) |
| 650 | >>> len(text1) |
| 651 | 4 |
| 652 | >>> text1[0][-1] |
| 653 | '\n' |
| 654 | >>> text2 = ''' 1. Beautiful is better than ugly. |
| 655 | ... 3. Simple is better than complex. |
| 656 | ... 4. Complicated is better than complex. |
| 657 | ... 5. Flat is better than nested. |
| 658 | ... '''.splitlines(1) |
| 659 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 660 | Next we instantiate a Differ object: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 661 | |
| 662 | >>> d = Differ() |
| 663 | |
| 664 | Note that when instantiating a :class:`Differ` object we may pass functions to |
| 665 | filter out line and character "junk." See the :meth:`Differ` constructor for |
| 666 | details. |
| 667 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 668 | Finally, we compare the two: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 669 | |
| 670 | >>> result = list(d.compare(text1, text2)) |
| 671 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 672 | ``result`` is a list of strings, so let's pretty-print it: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 673 | |
| 674 | >>> from pprint import pprint |
| 675 | >>> pprint(result) |
| 676 | [' 1. Beautiful is better than ugly.\n', |
| 677 | '- 2. Explicit is better than implicit.\n', |
| 678 | '- 3. Simple is better than complex.\n', |
| 679 | '+ 3. Simple is better than complex.\n', |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 680 | '? ++\n', |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 681 | '- 4. Complex is better than complicated.\n', |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 682 | '? ^ ---- ^\n', |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 683 | '+ 4. Complicated is better than complex.\n', |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 684 | '? ++++ ^ ^\n', |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 685 | '+ 5. Flat is better than nested.\n'] |
| 686 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 687 | As a single multi-line string it looks like this: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 688 | |
| 689 | >>> import sys |
| 690 | >>> sys.stdout.writelines(result) |
| 691 | 1. Beautiful is better than ugly. |
| 692 | - 2. Explicit is better than implicit. |
| 693 | - 3. Simple is better than complex. |
| 694 | + 3. Simple is better than complex. |
| 695 | ? ++ |
| 696 | - 4. Complex is better than complicated. |
| 697 | ? ^ ---- ^ |
| 698 | + 4. Complicated is better than complex. |
| 699 | ? ++++ ^ ^ |
| 700 | + 5. Flat is better than nested. |
| 701 | |
Christian Heimes | 8640e74 | 2008-02-23 16:23:06 +0000 | [diff] [blame] | 702 | |
| 703 | .. _difflib-interface: |
| 704 | |
| 705 | A command-line interface to difflib |
| 706 | ----------------------------------- |
| 707 | |
| 708 | This example shows how to use difflib to create a ``diff``-like utility. |
| 709 | It is also contained in the Python source distribution, as |
| 710 | :file:`Tools/scripts/diff.py`. |
| 711 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 712 | .. testcode:: |
Christian Heimes | 8640e74 | 2008-02-23 16:23:06 +0000 | [diff] [blame] | 713 | |
| 714 | """ Command line interface to difflib.py providing diffs in four formats: |
| 715 | |
| 716 | * ndiff: lists every line and highlights interline changes. |
| 717 | * context: highlights clusters of changes in a before/after format. |
| 718 | * unified: highlights clusters of changes in an inline format. |
| 719 | * html: generates side by side comparison with change highlights. |
| 720 | |
| 721 | """ |
| 722 | |
| 723 | import sys, os, time, difflib, optparse |
| 724 | |
| 725 | def main(): |
| 726 | # Configure the option parser |
| 727 | usage = "usage: %prog [options] fromfile tofile" |
| 728 | parser = optparse.OptionParser(usage) |
| 729 | parser.add_option("-c", action="store_true", default=False, |
| 730 | help='Produce a context format diff (default)') |
| 731 | parser.add_option("-u", action="store_true", default=False, |
| 732 | help='Produce a unified format diff') |
| 733 | hlp = 'Produce HTML side by side diff (can use -c and -l in conjunction)' |
| 734 | parser.add_option("-m", action="store_true", default=False, help=hlp) |
| 735 | parser.add_option("-n", action="store_true", default=False, |
| 736 | help='Produce a ndiff format diff') |
| 737 | parser.add_option("-l", "--lines", type="int", default=3, |
| 738 | help='Set number of context lines (default 3)') |
| 739 | (options, args) = parser.parse_args() |
| 740 | |
| 741 | if len(args) == 0: |
| 742 | parser.print_help() |
| 743 | sys.exit(1) |
| 744 | if len(args) != 2: |
| 745 | parser.error("need to specify both a fromfile and tofile") |
| 746 | |
| 747 | n = options.lines |
| 748 | fromfile, tofile = args # as specified in the usage string |
| 749 | |
| 750 | # we're passing these as arguments to the diff function |
| 751 | fromdate = time.ctime(os.stat(fromfile).st_mtime) |
| 752 | todate = time.ctime(os.stat(tofile).st_mtime) |
| 753 | fromlines = open(fromfile, 'U').readlines() |
| 754 | tolines = open(tofile, 'U').readlines() |
| 755 | |
| 756 | if options.u: |
| 757 | diff = difflib.unified_diff(fromlines, tolines, fromfile, tofile, |
| 758 | fromdate, todate, n=n) |
| 759 | elif options.n: |
| 760 | diff = difflib.ndiff(fromlines, tolines) |
| 761 | elif options.m: |
| 762 | diff = difflib.HtmlDiff().make_file(fromlines, tolines, fromfile, |
| 763 | tofile, context=options.c, |
| 764 | numlines=n) |
| 765 | else: |
| 766 | diff = difflib.context_diff(fromlines, tolines, fromfile, tofile, |
| 767 | fromdate, todate, n=n) |
| 768 | |
| 769 | # we're using writelines because diff is a generator |
| 770 | sys.stdout.writelines(diff) |
| 771 | |
| 772 | if __name__ == '__main__': |
| 773 | main() |