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