This is /home/pdm/install/Python-2.1/Doc/lib/python-lib.info, produced by makeinfo version 4.0 from lib.texi. April 15, 2001 2.1  File: python-lib.info, Node: Regular Expression Syntax, Next: Matching vs. Searching, Prev: re, Up: re Regular Expression Syntax ------------------------- A regular expression (or RE) specifies a set of strings that matches it; the functions in this module let you check if a particular string matches a given regular expression (or if a given regular expression matches a particular string, which comes down to the same thing). Regular expressions can be concatenated to form new regular expressions; if _A_ and _B_ are both regular expressions, then _AB_ is also an regular expression. If a string _p_ matches A and another string _q_ matches B, the string _pq_ will match AB. Thus, complex expressions can easily be constructed from simpler primitive expressions like the ones described here. For details of the theory and implementation of regular expressions, consult the Friedl book referenced below, or almost any textbook about compiler construction. A brief explanation of the format of regular expressions follows. For further information and a gentler presentation, consult the Regular Expression HOWTO, accessible from . Regular expressions can contain both special and ordinary characters. Most ordinary characters, like `A', `a', or `0', are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so "last" matches the string `'last''. (In the rest of this section, we'll write RE's in "this special style", usually without quotes, and strings to be matched `'in single quotes''.) Some characters, like `|' or `(', are special. Special characters either stand for classes of ordinary characters, or affect how the regular expressions around them are interpreted. The special characters are: ``.'' (Dot.) In the default mode, this matches any character except a newline. If the `DOTALL' flag has been specified, this matches any character including a newline. ``^'' (Caret.) Matches the start of the string, and in `MULTILINE' mode also matches immediately after each newline. ``$'' Matches the end of the string, and in `MULTILINE' mode also matches before a newline. "foo" matches both 'foo' and 'foobar', while the regular expression "foo$" matches only 'foo'. ``*'' Causes the resulting RE to match 0 or more repetitions of the preceding RE, as many repetitions as are possible. "ab*" will match 'a', 'ab', or 'a' followed by any number of 'b's. ``+'' Causes the resulting RE to match 1 or more repetitions of the preceding RE. "ab+" will match 'a' followed by any non-zero number of 'b's; it will not match just 'a'. ``?'' Causes the resulting RE to match 0 or 1 repetitions of the preceding RE. "ab?" will match either 'a' or 'ab'. ``*?', `+?', `??'' The `*', `+', and `?' qualifiers are all "greedy"; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE "<.*>" is matched against `'

title

'', it will match the entire string, and not just `'

''. Adding `?' after the qualifier makes it perform the match in "non-greedy" or "minimal" fashion; as _few_ characters as possible will be matched. Using ".*?" in the previous expression will match only `'

''. ``{M,N}'' Causes the resulting RE to match from M to N repetitions of the preceding RE, attempting to match as many repetitions as possible. For example, "a{3,5}" will match from 3 to 5 `a' characters. Omitting N specifies an infinite upper bound; you can't omit M. ``{M,N}?'' Causes the resulting RE to match from M to N repetitions of the preceding RE, attempting to match as _few_ repetitions as possible. This is the non-greedy version of the previous qualifier. For example, on the 6-character string `'aaaaaa'', "a{3,5}" will match 5 `a' characters, while "a{3,5}?" will only match 3 characters. ``\'' Either escapes special characters (permitting you to match characters like `*', `?', and so forth), or signals a special sequence; special sequences are discussed below. If you're not using a raw string to express the pattern, remember that Python also uses the backslash as an escape sequence in string literals; if the escape sequence isn't recognized by Python's parser, the backslash and subsequent character are included in the resulting string. However, if Python would recognize the resulting sequence, the backslash should be repeated twice. This is complicated and hard to understand, so it's highly recommended that you use raw strings for all but the simplest expressions. ``[ '] Used to indicate a set of characters. Characters can' be listed individually, or a range of characters can be indicated by giving two characters and separating them by a `-'. Special characters are not active inside sets. For example, "[akm$]" will match any of the characters `a', `k', `m', or `$'; "[a-z]" will match any lowercase letter, and `[a-zA-Z0-9]' matches any letter or digit. Character classes such as `\w' or `\S' (defined below) are also acceptable inside a range. If you want to include a `]' or a `-' inside a set, precede it with a backslash, or place it as the first character. The pattern "[]]" will match `']'', for example. You can match the characters not within a range by "complementing" the set. This is indicated by including a `^' as the first character of the set; `^' elsewhere will simply match the `^' character. For example, "[{^}5]" will match any character except `5'. ``|'' `A|B', where A and B can be arbitrary REs, creates a regular expression that will match either A or B. An arbitrary number of REs can be separated by the `|' in this way. This can be used inside groups (see below) as well. REs separated by `|' are tried from left to right, and the first one that allows the complete pattern to match is considered the accepted branch. This means that if `A' matches, `B' will never be tested, even if it would produce a longer overall match. In other words, the `|' operator is never greedy. To match a literal `|', use "\|", or enclose it inside a character class, as in "[|]". ``(...)'' Matches whatever regular expression is inside the parentheses, and indicates the start and end of a group; the contents of a group can be retrieved after a match has been performed, and can be matched later in the string with the "\NUMBER" special sequence, described below. To match the literals `(' or `)', use "\(" or "\)", or enclose them inside a character class: "[(] [)]". ``(?...)'' This is an extension notation (a `?' following a `(' is not meaningful otherwise). The first character after the `?' determines what the meaning and further syntax of the construct is. Extensions usually do not create a new group; "(?P...)" is the only exception to this rule. Following are the currently supported extensions. ``(?iLmsux)'' (One or more letters from the set `i', `L', `m', `s', `u', `x'.) The group matches the empty string; the letters set the corresponding flags (`re.I', `re.L', `re.M', `re.S', `re.U', `re.X') for the entire regular expression. This is useful if you wish to include the flags as part of the regular expression, instead of passing a FLAG argument to the `compile()' function. Note that the "(?x)" flag changes how the expression is parsed. It should be used first in the expression string, or after one or more whitespace characters. If there are non-whitespace characters before the flag, the results are undefined. ``(?:...)'' A non-grouping version of regular parentheses. Matches whatever regular expression is inside the parentheses, but the substring matched by the group _cannot_ be retrieved after performing a match or referenced later in the pattern. ``(?P...)'' Similar to regular parentheses, but the substring matched by the group is accessible via the symbolic group name NAME. Group names must be valid Python identifiers. A symbolic group is also a numbered group, just as if the group were not named. So the group named 'id' in the example above can also be referenced as the numbered group 1. For example, if the pattern is "(?P[a-zA-Z_]\w*)", the group can be referenced by its name in arguments to methods of match objects, such as `m.group('id')' or `m.end('id')', and also by name in pattern text (e.g. "(?P=id)") and replacement text (e.g. `\g'). ``(?P=NAME)'' Matches whatever text was matched by the earlier group named NAME. ``(?#...)'' A comment; the contents of the parentheses are simply ignored. ``(?=...)'' Matches if "..." matches next, but doesn't consume any of the string. This is called a lookahead assertion. For example, "Isaac (?=Asimov)" will match `'Isaac~'' only if it's followed by `'Asimov''. ``(?!...)'' Matches if "..." doesn't match next. This is a negative lookahead assertion. For example, "Isaac (?!Asimov)" will match `'Isaac~'' only if it's _not_ followed by `'Asimov''. ``(?<=...)'' Matches if the current position in the string is preceded by a match for "..." that ends at the current position. This is called a positive lookbehind assertion. "(?<=abc)def" will match `abcdef', since the lookbehind will back up 3 characters and check if the contained pattern matches. The contained pattern must only match strings of some fixed length, meaning that "abc" or "a|b" are allowed, but "a*" isn't. ``(?. Python offers two different primitive operations based on regular expressions: match and search. If you are accustomed to Perl's semantics, the search operation is what you're looking for. See the `search()' function and corresponding method of compiled regular expression objects. Note that match may differ from search using a regular expression beginning with `^': `^' matches only at the start of the string, or in `MULTILINE' mode also immediately following a newline. The "match" operation succeeds only if the pattern matches at the start of the string regardless of mode, or at the starting position given by the optional POS argument regardless of whether a newline precedes it. re.compile("a").match("ba", 1) # succeeds re.compile("^a").search("ba", 1) # fails; 'a' not at start re.compile("^a").search("\na", 1) # fails; 'a' not at start re.compile("^a", re.M).search("\na", 1) # succeeds re.compile("^a", re.M).search("ba", 1) # fails; no preceding \n  File: python-lib.info, Node: Contents of Module re, Next: Regular Expression Objects, Prev: Matching vs. Searching, Up: re Module Contents --------------- The module defines the following functions and constants, and an exception: `compile(pattern[, flags])' Compile a regular expression pattern into a regular expression object, which can be used for matching using its `match()' and `search()' methods, described below. The expression's behaviour can be modified by specifying a FLAGS value. Values can be any of the following variables, combined using bitwise OR (the `|' operator). The sequence prog = re.compile(pat) result = prog.match(str) is equivalent to result = re.match(pat, str) but the version using `compile()' is more efficient when the expression will be used several times in a single program. `I' `IGNORECASE' Perform case-insensitive matching; expressions like "[A-Z]" will match lowercase letters, too. This is not affected by the current locale. `L' `LOCALE' Make "\w", "\W", "\b", and "\B" dependent on the current locale. `M' `MULTILINE' When specified, the pattern character `^' matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character `$' matches at the end of the string and at the end of each line (immediately preceding each newline). By default, `^' matches only at the beginning of the string, and `$' only at the end of the string and immediately before the newline (if any) at the end of the string. `S' `DOTALL' Make the `.' special character match any character at all, including a newline; without this flag, `.' will match anything _except_ a newline. `U' `UNICODE' Make "\w", "\W", "\b", and "\B" dependent on the Unicode character properties database. _Added in Python version 2.0_ `X' `VERBOSE' This flag allows you to write regular expressions that look nicer. Whitespace within the pattern is ignored, except when in a character class or preceded by an unescaped backslash, and, when a line contains a `#' neither in a character class or preceded by an unescaped backslash, all characters from the leftmost such `#' through the end of the line are ignored. `search(pattern, string[, flags])' Scan through STRING looking for a location where the regular expression PATTERN produces a match, and return a corresponding `MatchObject' instance. Return `None' if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. `match(pattern, string[, flags])' If zero or more characters at the beginning of STRING match the regular expression PATTERN, return a corresponding `MatchObject' instance. Return `None' if the string does not match the pattern; note that this is different from a zero-length match. *Note:* If you want to locate a match anywhere in STRING, use `search()' instead. `split(pattern, string[, maxsplit` = 0'])' Split STRING by the occurrences of PATTERN. If capturing parentheses are used in PATTERN, then the text of all groups in the pattern are also returned as part of the resulting list. If MAXSPLIT is nonzero, at most MAXSPLIT splits occur, and the remainder of the string is returned as the final element of the list. (Incompatibility note: in the original Python 1.5 release, MAXSPLIT was ignored. This has been fixed in later releases.) >>> re.split('\W+', 'Words, words, words.') ['Words', 'words', 'words', ''] >>> re.split('(\W+)', 'Words, words, words.') ['Words', ', ', 'words', ', ', 'words', '.', ''] >>> re.split('\W+', 'Words, words, words.', 1) ['Words', 'words, words.'] This function combines and extends the functionality of the old `regsub.split()' and `regsub.splitx()'. `findall(pattern, string)' Return a list of all non-overlapping matches of PATTERN in STRING. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. _Added in Python version 1.5.2_ `sub(pattern, repl, string[, count` = 0'])' Return the string obtained by replacing the leftmost non-overlapping occurrences of PATTERN in STRING by the replacement REPL. If the pattern isn't found, STRING is returned unchanged. REPL can be a string or a function; if a function, it is called for every non-overlapping occurrence of PATTERN. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj): .... if matchobj.group(0) == '-': return ' ' .... else: return '-' >>> re.sub('-{1,2}', dashrepl, 'pro----gram-files') 'pro--gram files' The pattern may be a string or a regex object; if you need to specify regular expression flags, you must use a regex object, or use embedded modifiers in a pattern; e.g. `sub("(?i)b+", "x", "bbbb BBBB")' returns `'x x''. The optional argument COUNT is the maximum number of pattern occurrences to be replaced; COUNT must be a non-negative integer, and the default value of 0 means to replace all occurrences. Empty matches for the pattern are replaced only when not adjacent to a previous match, so `sub('x*', '-', 'abc')' returns `'-a-b-c-''. If REPL is a string, any backslash escapes in it are processed. That is, `\n' is converted to a single newline character, `\r' is converted to a linefeed, and so forth. Unknown escapes such as `\j' are left alone. Backreferences, such as `\6', are replaced with the substring matched by group 6 in the pattern. In addition to character escapes and backreferences as described above, `\g' will use the substring matched by the group named `name', as defined by the "(?P...)" syntax. `\g' uses the corresponding group number; `\g<2>' is therefore equivalent to `\2', but isn't ambiguous in a replacement such as `\g<2>0'. `\20' would be interpreted as a reference to group 20, not a reference to group 2 followed by the literal character `0'. `subn(pattern, repl, string[, count` = 0'])' Perform the same operation as `sub()', but return a tuple `(NEW_STRING, NUMBER_OF_SUBS_MADE)'. `escape(string)' Return STRING with all non-alphanumerics backslashed; this is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it. `error' Exception raised when a string passed to one of the functions here is not a valid regular expression (e.g., unmatched parentheses) or when some other error occurs during compilation or matching. It is never an error if a string contains no match for a pattern.  File: python-lib.info, Node: Regular Expression Objects, Next: Match Objects, Prev: Contents of Module re, Up: re Regular Expression Objects -------------------------- Compiled regular expression objects support the following methods and attributes: `search(string[, pos[, endpos]])' Scan through STRING looking for a location where this regular expression produces a match, and return a corresponding `MatchObject' instance. Return `None' if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string. The optional POS and ENDPOS parameters have the same meaning as for the `match()' method. `match(string[, pos[, endpos]])' If zero or more characters at the beginning of STRING match this regular expression, return a corresponding `MatchObject' instance. Return `None' if the string does not match the pattern; note that this is different from a zero-length match. *Note:* If you want to locate a match anywhere in STRING, use `search()' instead. The optional second parameter POS gives an index in the string where the search is to start; it defaults to `0'. This is not completely equivalent to slicing the string; the `'^'' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start. The optional parameter ENDPOS limits how far the string will be searched; it will be as if the string is ENDPOS characters long, so only the characters from POS to ENDPOS will be searched for a match. `split(string[, maxsplit` = 0'])' Identical to the `split()' function, using the compiled pattern. `findall(string)' Identical to the `findall()' function, using the compiled pattern. `sub(repl, string[, count` = 0'])' Identical to the `sub()' function, using the compiled pattern. `subn(repl, string[, count` = 0'])' Identical to the `subn()' function, using the compiled pattern. `flags' The flags argument used when the regex object was compiled, or `0' if no flags were provided. `groupindex' A dictionary mapping any symbolic group names defined by "(?P)" to group numbers. The dictionary is empty if no symbolic groups were used in the pattern. `pattern' The pattern string from which the regex object was compiled.  File: python-lib.info, Node: Match Objects, Prev: Regular Expression Objects, Up: re Match Objects ------------- `MatchObject' instances support the following methods and attributes: `expand(template)' Return the string obtained by doing backslash substitution on the template string TEMPLATE, as done by the `sub()' method. Escapes such as `\n' are converted to the appropriate characters, and numeric backreferences (`\1', `\2') and named backreferences (`\g<1>', `\g') are replaced by the contents of the corresponding group. `group([group1, ...])' Returns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, GROUP1 defaults to zero (i.e. the whole match is returned). If a GROUPN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an `IndexError' exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is `-1'. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. If the regular expression uses the "(?P...)" syntax, the GROUPN arguments may also be strings identifying groups by their group name. If a string argument is not used as a group name in the pattern, an `IndexError' exception is raised. A moderately complicated example: m = re.match(r"(?P\d+)\.(\d*)", '3.14') After performing this match, `m.group(1)' is `'3'', as is `m.group('int')', and `m.group(2)' is `'14''. `groups([default])' Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The DEFAULT argument is used for groups that did not participate in the match; it defaults to `None'. (Incompatibility note: in the original Python 1.5 release, if the tuple was one element long, a string would be returned instead. In later versions (from 1.5.1 on), a singleton tuple is returned in such cases.) `groupdict([default])' Return a dictionary containing all the _named_ subgroups of the match, keyed by the subgroup name. The DEFAULT argument is used for groups that did not participate in the match; it defaults to `None'. `start([group])' `end [group]' Return the indices of the start and end of the substring matched by GROUP; GROUP defaults to zero (meaning the whole matched substring). Return `-1' if GROUP exists but did not contribute to the match. For a match object M, and a group G that did contribute to the match, the substring matched by group G (equivalent to `M.group(G)') is m.string[m.start(g):m.end(g)] Note that `m.start(GROUP)' will equal `m.end(GROUP)' if GROUP matched a null string. For example, after `M = re.search('b(c?)', 'cba')', `M.start(0)' is 1, `M.end(0)' is 2, `M.start(1)' and `M.end(1)' are both 2, and `M.start(2)' raises an `IndexError' exception. `span([group])' For `MatchObject' M, return the 2-tuple `(M.start(GROUP), M.end(GROUP))'. Note that if GROUP did not contribute to the match, this is `(-1, -1)'. Again, GROUP defaults to zero. `pos' The value of POS which was passed to the `search()' or `match()' function. This is the index into the string at which the regex engine started looking for a match. `endpos' The value of ENDPOS which was passed to the `search()' or `match()' function. This is the index into the string beyond which the regex engine will not go. `lastgroup' The name of the last matched capturing group, or `None' if the group didn't have a name, or if no group was matched at all. `lastindex' The integer index of the last matched capturing group, or `None' if no group was matched at all. `re' The regular expression object whose `match()' or `search()' method produced this `MatchObject' instance. `string' The string passed to `match()' or `search()'.  File: python-lib.info, Node: struct, Next: difflib, Prev: re, Up: String Services Interpret strings as packed binary data ======================================= Interpret strings as packed binary data. This module performs conversions between Python values and C structs represented as Python strings. It uses "format strings" (explained below) as compact descriptions of the lay-out of the C structs and the intended conversion to/from Python values. This can be used in handling binary data stored in files or from network connections, among other sources. The module defines the following exception and functions: `error' Exception raised on various occasions; argument is a string describing what is wrong. `pack(fmt, v1, v2, ...)' Return a string containing the values `V1, V2, ...' packed according to the given format. The arguments must match the values required by the format exactly. `unpack(fmt, string)' Unpack the string (presumably packed by `pack(FMT, ...)') according to the given format. The result is a tuple even if it contains exactly one item. The string must contain exactly the amount of data required by the format (i.e. `len(STRING)' must equal `calcsize(FMT)'). `calcsize(fmt)' Return the size of the struct (and hence of the string) corresponding to the given format. Format characters have the following meaning; the conversion between C and Python values should be obvious given their types: Format C Type Python Notes ------ ------ ------ ------ x pad byte no value c `char' string of length 1 b `signed char' integer B `unsigned char' integer h `short' integer H `unsigned short' integer i `int' integer I `unsigned int' long (1) l `long' integer L `unsigned long' long f `float' float d `double' float s `char[]' string p `char[]' string P `void *' integer Notes: `(1)' The `I' conversion code will convert to a Python long if the C `int' is the same size as a C `long', which is typical on most modern systems. If a C `int' is smaller than a C `long', an Python integer will be created instead. A format character may be preceded by an integral repeat count; e.g. the format string `'4h'' means exactly the same as `'hhhh''. Whitespace characters between formats are ignored; a count and its format must not contain whitespace though. For the `s' format character, the count is interpreted as the size of the string, not a repeat count like for the other format characters; e.g. `'10s'' means a single 10-byte string, while `'10c'' means 10 characters. For packing, the string is truncated or padded with null bytes as appropriate to make it fit. For unpacking, the resulting string always has exactly the specified number of bytes. As a special case, `'0s'' means a single, empty string (while `'0c'' means 0 characters). The `p' format character can be used to encode a Pascal string. The first byte is the length of the stored string, with the bytes of the string following. If count is given, it is used as the total number of bytes used, including the length byte. If the string passed in to `pack()' is too long, the stored representation is truncated. If the string is too short, padding is used to ensure that exactly enough bytes are used to satisfy the count. For the `I' and `L' format characters, the return value is a Python long integer. For the `P' format character, the return value is a Python integer or long integer, depending on the size needed to hold a pointer when it has been cast to an integer type. A `NULL' pointer will always be returned as the Python integer `0'. When packing pointer-sized values, Python integer or long integer objects may be used. For example, the Alpha and Merced processors use 64-bit pointer values, meaning a Python long integer will be used to hold the pointer; other platforms use 32-bit pointers and will use a Python integer. By default, C numbers are represented in the machine's native format and byte order, and properly aligned by skipping pad bytes if necessary (according to the rules used by the C compiler). Alternatively, the first character of the format string can be used to indicate the byte order, size and alignment of the packed data, according to the following table: Character Byte order Size and alignment ------ ----- ----- @ native native = native standard < little-endian standard > big-endian standard ! network (= big-endian) standard If the first character is not one of these, `@' is assumed. Native byte order is big-endian or little-endian, depending on the host system (e.g. Motorola and Sun are big-endian; Intel and DEC are little-endian). Native size and alignment are determined using the C compiler's `sizeof' expression. This is always combined with native byte order. Standard size and alignment are as follows: no alignment is required for any type (so you have to use pad bytes); `short' is 2 bytes; `int' and `long' are 4 bytes. `float' and `double' are 32-bit and 64-bit IEEE floating point numbers, respectively. Note the difference between `@' and `=': both use native byte order, but the size and alignment of the latter is standardized. The form `!' is available for those poor souls who claim they can't remember whether network byte order is big-endian or little-endian. There is no way to indicate non-native byte order (i.e. force byte-swapping); use the appropriate choice of `<' or `>'. The `P' format character is only available for the native byte ordering (selected as the default or with the `@' byte order character). The byte order character `=' chooses to use little- or big-endian ordering based on the host system. The struct module does not interpret this as native ordering, so the `P' format is not available. Examples (all using native byte order, size and alignment, on a big-endian machine): >>> from struct import * >>> pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) >>> calcsize('hhl') 8 Hint: to align the end of a structure to the alignment requirement of a particular type, end the format with the code for that type with a repeat count of zero, e.g. the format `'llh0l'' specifies two pad bytes at the end, assuming longs are aligned on 4-byte boundaries. This only works when native size and alignment are in effect; standard size and alignment does not enforce any alignment. See also: *Note array:: Packed binary storage of homogeneous data. *Note xdrlib:: Packing and unpacking of XDR data.  File: python-lib.info, Node: difflib, Next: fpformat, Prev: struct, Up: String Services Helpers for computing deltas ============================ Helpers for computing differences between objects. This module was documented by Tim Peters . This section was written by Tim Peters . _Added in Python version 2.1_ `get_close_matches(word, possibilities[, n[, cutoff]])' Return a list of the best "good enough" matches. WORD is a sequence for which close matches are desired (typically a string), and POSSIBILITIES is a list of sequences against which to match WORD (typically a list of strings). Optional argument N (default `3') is the maximum number of close matches to return; N must be greater than `0'. Optional argument CUTOFF (default `0.6') is a float in the range [0, 1]. Possibilities that don't score at least that similar to WORD are ignored. The best (no more than N) matches among the possibilities are returned in a list, sorted by similarity score, most similar first. >>> get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] >>> import keyword >>> get_close_matches('wheel', keyword.kwlist) ['while'] >>> get_close_matches('apple', keyword.kwlist) [] >>> get_close_matches('accept', keyword.kwlist) ['except'] `SequenceMatcher(...)' This is a flexible class for comparing pairs of sequences of any type, so long as the sequence elements are hashable. The basic algorithm predates, and is a little fancier than, an algorithm published in the late 1980's by Ratcliff and Obershelp under the hyperbolic name "gestalt pattern matching." The idea is to find the longest contiguous matching subsequence that contains no "junk" elements (the Ratcliff and Obershelp algorithm doesn't address junk). The same idea is then applied recursively to the pieces of the sequences to the left and to the right of the matching subsequence. This does not yield minimal edit sequences, but does tend to yield matches that "look right" to people. *Timing:* The basic Ratcliff-Obershelp algorithm is cubic time in the worst case and quadratic time in the expected case. `SequenceMatcher' is quadratic time for the worst case and has expected-case behavior dependent in a complicated way on how many elements the sequences have in common; best case time is linear. See also: `Pattern Matching: The Gestalt Approach'{Discussion of a similar algorithm by John W. Ratcliff and D. E. Metzener. This was published in in July, 1988.} * Menu: * SequenceMatcher Objects:: * Examples 2::  File: python-lib.info, Node: SequenceMatcher Objects, Next: Examples 2, Prev: difflib, Up: difflib SequenceMatcher Objects ----------------------- `SequenceMatcher([isjunk[, a[, b]]])' Optional argument ISJUNK must be `None' (the default) or a one-argument function that takes a sequence element and returns true if and only if the element is "junk" and should be ignored. `None' is equivalent to passing `lambda x: 0', i.e. no elements are ignored. For example, pass lambda x: x in " \t" if you're comparing lines as sequences of characters, and don't want to synch up on blanks or hard tabs. The optional arguments A and B are sequences to be compared; both default to empty strings. The elements of both sequences must be hashable. `SequenceMatcher' objects have the following methods: `set_seqs(a, b)' Set the two sequences to be compared. `SequenceMatcher' computes and caches detailed information about the second sequence, so if you want to compare one sequence against many sequences, use `set_seq2()' to set the commonly used sequence once and call `set_seq1()' repeatedly, once for each of the other sequences. `set_seq1(a)' Set the first sequence to be compared. The second sequence to be compared is not changed. `set_seq2(b)' Set the second sequence to be compared. The first sequence to be compared is not changed. `find_longest_match(alo, ahi, blo, bhi)' Find longest matching block in `A[ALO:AHI]' and `B[BLO:BHI]'. If ISJUNK was omitted or `None', `get_longest_match()' returns `(I, J, K)' such that `A[I:I+K]' is equal to `B[J:J+K]', where `ALO <= I <= I+K <= AHI' and `BLO <= J <= J+K <= BHI'. For all `(I', J', K')' meeting those conditions, the additional conditions `K >= K'', `I <= I'', and if `I == I'', `J <= J'' are also met. In other words, of all maximal matching blocks, return one that starts earliest in A, and of all those maximal matching blocks that start earliest in A, return the one that starts earliest in B. >>> s = SequenceMatcher(None, " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) (0, 4, 5) If ISJUNK was provided, first the longest matching block is determined as above, but with the additional restriction that no junk element appears in the block. Then that block is extended as far as possible by matching (only) junk elements on both sides. So the resulting block never matches on junk except as identical junk happens to be adjacent to an interesting match. Here's the same example as before, but considering blanks to be junk. That prevents `' abcd'' from matching the `' abcd'' at the tail end of the second sequence directly. Instead only the `'abcd'' can match, and matches the leftmost `'abcd'' in the second sequence: >>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd") >>> s.find_longest_match(0, 5, 0, 9) (1, 0, 4) If no blocks match, this returns `(ALO, BLO, 0)'. `get_matching_blocks()' Return list of triples describing matching subsequences. Each triple is of the form `(I, J, N)', and means that `A[I:I+N] == B[J:J+N]'. The triples are monotonically increasing in I and J. The last triple is a dummy, and has the value `(len(A), len(B), 0)'. It is the only triple with `N == 0'. >>> s = SequenceMatcher(None, "abxcd", "abcd") >>> s.get_matching_blocks() [(0, 0, 2), (3, 2, 2), (5, 4, 0)] `get_opcodes()' Return list of 5-tuples describing how to turn A into B. Each tuple is of the form `(TAG, I1, I2, J1, J2)'. The first tuple has `I1 == J1 == 0', and remaining tuples have I1 equal to the I2 from the preceeding tuple, and, likewise, J1 equal to the previous J2. The TAG values are strings, with these meanings: Value Meaning ------ ----- 'replace' `A[I1:I2]' should be replaced by `B[J1:J2]'. 'delete' `A[I1:I2]' should be deleted. Note that `J1 == J2' in this case. 'insert' `B[J1:J2]' should be inserted at `A[I1:I1]'. Note that `I1 == I2' in this case. 'equal' `A[I1:I2] == B[J1:J2]' (the sub-sequences are equal). For example: >>> a = "qabxcd" >>> b = "abycdf" >>> s = SequenceMatcher(None, a, b) >>> for tag, i1, i2, j1, j2 in s.get_opcodes(): ... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" % ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])) delete a[0:1] (q) b[0:0] () equal a[1:3] (ab) b[0:2] (ab) replace a[3:4] (x) b[2:3] (y) equal a[4:6] (cd) b[3:5] (cd) insert a[6:6] () b[5:6] (f) `ratio()' Return a measure of the sequences' similarity as a float in the range [0, 1]. Where T is the total number of elements in both sequences, and M is the number of matches, this is 2.0*M / T. Note that this is `1.' if the sequences are identical, and `0.' if they have nothing in common. This is expensive to compute if `get_matching_blocks()' or `get_opcodes()' hasn't already been called, in which case you may want to try `quick_ratio()' or `real_quick_ratio()' first to get an upper bound. `quick_ratio()' Return an upper bound on `ratio()' relatively quickly. This isn't defined beyond that it is an upper bound on `ratio()', and is faster to compute. `real_quick_ratio()' Return an upper bound on `ratio()' very quickly. This isn't defined beyond that it is an upper bound on `ratio()', and is faster to compute than either `ratio()' or `quick_ratio()'. The three methods that return the ratio of matching to total characters can give different results due to differing levels of approximation, although `quick_ratio()' and `real_quick_ratio()' are always at least as large as `ratio()': >>> s = SequenceMatcher(None, "abcd", "bcde") >>> s.ratio() 0.75 >>> s.quick_ratio() 0.75 >>> s.real_quick_ratio() 1.0  File: python-lib.info, Node: Examples 2, Prev: SequenceMatcher Objects, Up: difflib Examples -------- This example compares two strings, considering blanks to be "junk:" >>> s = SequenceMatcher(lambda x: x == " ", ... "private Thread currentThread;", ... "private volatile Thread currentThread;") `ratio()' returns a float in [0, 1], measuring the similarity of the sequences. As a rule of thumb, a `ratio()' value over 0.6 means the sequences are close matches: >>> print round(s.ratio(), 3) 0.866 If you're only interested in where the sequences match, `get_matching_blocks()' is handy: >>> for block in s.get_matching_blocks(): ... print "a[%d] and b[%d] match for %d elements" % block a[0] and b[0] match for 8 elements a[8] and b[17] match for 6 elements a[14] and b[23] match for 15 elements a[29] and b[38] match for 0 elements Note that the last tuple returned by `get_matching_blocks()' is always a dummy, `(len(A), len(B), 0)', and this is the only case in which the last tuple element (number of elements matched) is `0'. If you want to know how to change the first sequence into the second, use `get_opcodes()': >>> for opcode in s.get_opcodes(): ... print "%6s a[%d:%d] b[%d:%d]" % opcode equal a[0:8] b[0:8] insert a[8:8] b[8:17] equal a[8:14] b[17:23] equal a[14:29] b[23:38] See `Tools/scripts/ndiff.py' from the Python source distribution for a fancy human-friendly file differencer, which uses `SequenceMatcher' both to view files as sequences of lines, and lines as sequences of characters. See also the function `get_close_matches()' in this module, which shows how simple code building on `SequenceMatcher' can be used to do useful work.  File: python-lib.info, Node: fpformat, Next: StringIO, Prev: difflib, Up: String Services Floating point conversions ========================== This section was written by Moshe Zadka . General floating point formatting functions. The `fpformat' module defines functions for dealing with floating point numbers representations in 100% pure Python. *Note:* This module is unneeded: everything here could be done via the `%' string interpolation operator. The `fpformat' module defines the following functions and an exception: `fix(x, digs)' Format X as `[-]ddd.ddd' with DIGS digits after the point and at least one digit before. If `DIGS <= 0', the decimal point is suppressed. X can be either a number or a string that looks like one. DIGS is an integer. Return value is a string. `sci(x, digs)' Format X as `[-]d.dddE[+-]ddd' with DIGS digits after the point and exactly one digit before. If `DIGS <= 0', one digit is kept and the point is suppressed. X can be either a real number, or a string that looks like one. DIGS is an integer. Return value is a string. `NotANumber' Exception raised when a string passed to `fix()' or `sci()' as the X parameter does not look like a number. This is a subclass of `ValueError' when the standard exceptions are strings. The exception value is the improperly formatted string that caused the exception to be raised. Example: >>> import fpformat >>> fpformat.fix(1.23, 1) '1.2'