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