fuzzywuzzy-0.10.0/0000755000076500000240000000000012671432702014177 5ustar josestaff00000000000000fuzzywuzzy-0.10.0/CHANGES.rst0000644000076500000000000003156412671432677016020 0ustar josewheel00000000000000Changelog ========= 0.10.0 (2016-03-13) ------------------- - Handle None inputs same as empty string (Issue #94) [Nick Miller] 0.9.0 (2016-03-07) ------------------ - Pull down all keys when updating local copy. [Jose Diaz-Gonzalez] 0.8.2 (2016-02-26) ------------------ - Remove the warning for "slow" sequence matcher on PyPy. [Julian Berman] where it's preferable to use the pure-python implementation. 0.8.1 (2016-01-25) ------------------ - Minor release changes. [Jose Diaz-Gonzalez] - Clean up wiki link in readme. [Ewan Oglethorpe] 0.8.0 (2015-11-16) ------------------ - Refer to Levenshtein distance in readme. Closes #88. [Jose Diaz- Gonzalez] - Added install step for travis to have pep8 available. [Pedro Rodrigues] - Added a pep8 test. The way I add the error 501 to the ignore tuple is probably wrong but from the docs and source code of pep8 I could not find any other way. [Pedro Rodrigues] I also went ahead and removed the pep8 call from the release file. - Added python 3.5, pypy, and ypyp3 to the travis config file. [Pedro Rodrigues] - Added another step to the release file to run the tests before releasing. [Pedro Rodrigues] - Fixed a few pep8 errors Added a verification step in the release automation file. This step should probably be somewhere at git level. [Pedro Rodrigues] - Pep8. [Pedro Rodrigues] - Leaving TODOs in the code was never a good idea. [Pedro Rodrigues] - Changed return values to be rounded integers. [Pedro Rodrigues] - Added a test with the recovered data file. [Pedro Rodrigues] - Recovered titledata.csv. [Pedro Rodrigues] - Move extract test methods into the process test. [Shale Craig] Somehow, they ended up in the `RatioTest`, despite asserting that the `ProcessTest` works. 0.7.0 (2015-10-02) ------------------ - Use portable syntax for catching exception on tests. [Luis Madrigal] - [Fix] test against correct variable. [Luis Madrigal] - Add unit tests for validator decorators. [Luis Madrigal] - Move validators to decorator functions. [Luis Madrigal] This allows easier composition and IMO makes the functions more readable - Fix typo: dictionery -> dictionary. [shale] - FizzyWuzzy -> FuzzyWuzzy typo correction. [shale] - Add check for gitchangelog. [Jose Diaz-Gonzalez] 0.6.2 (2015-09-03) ------------------ - Ensure the rst-lint binary is available. [Jose Diaz-Gonzalez] 0.6.1 (2015-08-07) ------------------ - Minor whitespace changes for PEP8. [Jose Diaz-Gonzalez] 0.6.0 (2015-07-20) ------------------ - Added link to a java port. [Andriy Burkov] - Patched "name 'unicode' is not defined" python3. [Carlos Garay] https://github.com/seatgeek/fuzzywuzzy/issues/80 - Make process.extract accept {dict, list}-like choices. [Nathan Typanski] Previously, process.extract expected lists or dictionaries, and tested this with isinstance() calls. In keeping with the spirit of Python (duck typing and all that), this change enables one to use extract() on any dict-like object for dict-like results, or any list-like object for list-like results. So now we can (and, indeed, I've added tests for these uses) call extract() on things like: - a generator of strings ("any iterable") - a UserDict - custom user-made classes that "look like" dicts (or, really, anything with a .items() method that behaves like a dict) - plain old lists and dicts The behavior is exactly the same for previous use cases of lists-and-dicts. This change goes along nicely with PR #68, since those docs suggest dict-like behavior is valid, and this change makes that true. - Merge conflict. [Adam Cohen] - Improve docs for fuzzywuzzy.process. [Nathan Typanski] The documentation for this module was dated and sometimes inaccurate. This overhauls the docs to accurately describe the current module, including detailing optional arguments that were not previously explained - e.g., limit argument to extract(). This change follows the Google Python Style Guide, which may be found at: 0.5.0 (2015-02-04) ------------------ - FIX: 0.4.0 is released, no need to specify 0.3.1 in README. [Josh Warner (Mac)] - Fixed a small typo. [Rostislav Semenov] - Reset `processor` and `scorer` defaults to None with argument checking. [foxxyz] - Catch generators without lengths. [Jeremiah Lowin] - Fixed python3 issue and deprecated assertion method. [foxxyz] - Fixed some docstrings, typos, python3 string method compatibility, some errors that crept in during rebase. [foxxyz] - [mod] The lamdba in extract is not needed. [Olivier Le Thanh Duong] [mod] Pass directly the defaults functions in the args [mod] itertools.takewhile() can handle empty list just fine no need to test for it [mod] Shorten extractOne by removing double if [mod] Use a list comprehention in extract() [mod] Autopep8 on process.py [doc] Document make_type_consistent [mod] bad_chars shortened [enh] Move regex compilation outside the method, otherwhise we don't get the benefit from it [mod] Don't need all the blah just to redefine method from string module [mod] Remove unused import [mod] Autopep8 on string_processing.py [mod] Rewrote asciidammit without recursion to make it more readable [mod] Autopep8 on utils.py [mod] Remove unused import [doc] Add some doc to fuzz.py [mod] Move the code to sort string in a separate function [doc] Docstrings for WRatio, UWRatio - Add note on which package to install. Closes #67. [Jose Diaz-Gonzalez] 0.4.0 (2014-10-31) ------------------ - In extarctBests() and extractOne() use '>=' instead of '>' [Юрий Пайков] - Fixed python3 issue with SequenceMatcher import. [Юрий Пайков] 0.3.3 (2014-10-22) ------------------ - Fixed issue #59 - "partial" parameter for `_token_set()` is now honored. [Юрий Пайков] - Catch generators without lengths. [Jeremiah Lowin] - Remove explicit check for lists. [Jeremiah Lowin] The logic in `process.extract()` should support any Python sequence/iterable. The explicit check for lists is unnecessary and limiting (for example, it forces conversion of generators and other iterable classes to lists). 0.3.2 (2014-09-12) ------------------ - Make release command an executable. [Jose Diaz-Gonzalez] - Simplify MANIFEST.in. [Jose Diaz-Gonzalez] - Add a release script. [Jose Diaz-Gonzalez] - Fix readme codeblock. [Jose Diaz-Gonzalez] - Minor formatting. [Jose Diaz-Gonzalez] - Use __version__ from fuzzywuzzy package. [Jose Diaz-Gonzalez] - Set __version__ constant in __init__.py. [Jose Diaz-Gonzalez] - Rename LICENSE to LICENSE.txt. [Jose Diaz-Gonzalez] 0.3.0 (2014-08-24) ------------------ - Test dict input to extractOne() [jamesnunn] - Remove whitespace. [jamesnunn] - Choices parameter for extract() accepts both dict and list objects. [jamesnunn] - Enable automated testing with Python 3.4. [Corey Farwell] - Fixed typo: lettters -> letters. [Tal Einat] - Fixing LICENSE and README's license info. [Dallas Gutauckis] - Proper ordered list. [Jeff Paine] - Convert README to rst. [Jeff Paine] - Add requirements.txt per discussion in #44. [Jeff Paine] - Add LICENSE TO MANIFEST.in. [Jeff Paine] - Rename tests.py to more common test_fuzzywuzzy.py. [Jeff Paine] - Add proper MANIFEST template. [Jeff Paine] - Remove MANIFEST file Not meant to be kept in version control. [Jeff Paine] - Remove unused file. [Jeff Paine] - Pep8. [Jeff Paine] - Pep8 formatting. [Jeff Paine] - Pep8 formatting. [Jeff Paine] - Pep8 indentations. [Jeff Paine] - Pep8 cleanup. [Jeff Paine] - Pep8. [Jeff Paine] - Pep8 cleanup. [Jeff Paine] - Pep8 cleanup. [Jeff Paine] - Pep8 import style. [Jeff Paine] - Pep8 import ordering. [Jeff Paine] - Pep8 import ordering. [Jeff Paine] - Remove unused module. [Jeff Paine] - Pep8 import ordering. [Jeff Paine] - Remove unused module. [Jeff Paine] - Pep8 import ordering. [Jeff Paine] - Remove unused imports. [Jeff Paine] - Remove unused module. [Jeff Paine] - Remove import * where present. [Jeff Paine] - Avoid import * [Jeff Paine] - Add Travis CI badge. [Jeff Paine] - Remove python 2.4, 2.5 from Travis (not supported) [Jeff Paine] - Add python 2.4 and 2.5 to Travis. [Jeff Paine] - Add all supported python versions to travis. [Jeff Paine] - Bump minor version number. [Jeff Paine] - Add classifiers for python versions. [Jeff Paine] - Added note about python-Levenshtein speedup. Closes #34. [Jose Diaz- Gonzalez] - Fixed tests on 2.6. [Grigi] - Fixed py2.6. [Grigi] - Force bad_chars to ascii. [Grigi] - Since importing unicode_literals, u decorator not required on strings from py2.6 and up. [Grigi] - Py3 support without 2to3. [Grigi] - Created: Added .travis.yml. [futoase] - [enh] Add docstrings to process.py. [Olivier Le Thanh Duong] Turn the existings comments into docstrings so they can be seen via introspection - Don't condense multiple punctuation characters to a single whitespace. this is a behavioral change. [Adam Cohen] - UQRatio and UWRatio shorthands. [Adam Cohen] - Version 0.2. [Adam Cohen] - Unicode/string comparison bug. [Adam Cohen] - To maintain backwards compatibility, default is to force_ascii as before. [Adam Cohen] - Fix merge conflict. [Adam Cohen] - New process function: extractBests. [Flávio Juvenal] - More readable reverse sorting. [Flávio Juvenal] - Further honoring of force_ascii. [Adam Cohen] - Indentation fix. [Adam Cohen] - Handle force_ascii in fuzz methods. [Adam Cohen] - Add back relevant tests. [Adam Cohen] - Utility method to make things consistent. [Adam Cohen] - Re-commit asciidammit and add a parameter to full_process to determine behavior. [Adam Cohen] - Added a test for non letters/digits replacements. [Tristan Launay] - ENG-741 fixed benchmark line length. [Laurent Erignoux] - Fixed Unicode flag for tests. [Tristan Launay] - ENG-741 commented code removed not erased for review from creator. [Laurent Erignoux] - ENG-741 cut long lines in fuzzy wizzy benchmark. [Laurent Erignoux] - Re-upped the limit on benchmark, now that performance is not an issue anymore. [Tristan Launay] - Fixed comment. [Tristan Launay] - Simplified processing of strings with built-in regex code in python. Also fixed empty string detection in token_sort_ratio. [Tristan Launay] - Proper benchmark display. Introduce methods to explicitly do all the unicode preprocessing *before* using fuzz lib. [Tristan Launay] - ENG-741: having a true benchmark, to see when we improve stuff. [Benjamin Combourieu] - Unicode support in benchmark.py. [Benjamin Combourieu] - Added file for processing strings. [Tristan Launay] - Uniform treatment of strings in Unicode. Non-ASCII chars are now considered in strings, which allows for matches in Cyrillic, Chinese, Greek, etc. [Tristan Launay] - Fixed bug in _token_set. [Michael Edward] - Removed reference to PR. [Jose Diaz-Gonzalez] - Sadist build and virtualenv dirs are not part of the project. [Pedro Rodrigues] - Fixes https://github.com/seatgeek/fuzzywuzzy/issues/10 and correctly points to README.textile. [Pedro Rodrigues] - Info on the pull request. [Pedro Rodrigues] - Pullstat.us button. [Pedro Rodrigues] - Fuzzywuzzy really needs better benchmarks. [Pedro Rodrigues] - Moved tests and benchmarks out of the package. [Pedro Rodrigues] - Report better ratio()s redundant import try. [Pedro Rodrigues] - AssertGreater did not exist in python 2.4. [Pedro Rodrigues] - Remove debug output. [Adam Cohen] - Looks for python-Levenshtein package, and if present, uses that instead of difflib. 10x speedup if present. add benchmarks. [Adam Cohen] - Add gitignore. [Adam Cohen] - Fix a bug in WRatio, as well as an issue in full_process, which was failing on strings with all unicode characters. [Adam Cohen] - Error in partial_ratio. closes #7. [Adam Cohen] - Adding some real-life event data for benchmarking. [Adam Cohen] - Cleaned up utils.py. [Pedro Rodrigues] - Optimized speed for full_process() [Pedro Rodrigues] - Speed improvements to asciidammit. [Pedro Rodrigues] - Removed old versions of validate_string() and remove_ponctuation() kept from previous commits. [Pedro Rodrigues] - Issue #6 from github updated license headers to match MIT license. [Pedro Rodrigues] - Clean up. [Pedro Rodrigues] - Changes to utils.validate_string() and benchmarks. [Pedro Rodrigues] - Some benchmarks to test the changes made to remove_punctuation. [Pedro Rodrigues] - Faster remove_punctuation. [Pedro Rodrigues] - AssertIsNone did not exist in Python 2.4. [Pedro Rodrigues] - Just adding some simple install instructions for pip. [Chris Dary] - Check for null/empty strings in QRatio and WRatio. Add tests. Closes #3. [Adam Cohen] - More README. [Adam Cohen] - README. [Adam Cohen] - README. [Adam Cohen] - Slight change to README. [Adam Cohen] - Some readme. [Adam Cohen] - Distutils. [Adam Cohen] - Change directory structure. [Adam Cohen] - Initial commit. [Adam Cohen] fuzzywuzzy-0.10.0/fuzzywuzzy/0000755000076500000240000000000012671432702016517 5ustar josestaff00000000000000fuzzywuzzy-0.10.0/fuzzywuzzy/__init__.py0000600000076500000000000000005712671432677020630 0ustar josewheel00000000000000# -*- coding: utf-8 -*- __version__ = '0.10.0' fuzzywuzzy-0.10.0/fuzzywuzzy/fuzz.py0000644000076500000240000001764312664107614020105 0ustar josestaff00000000000000#!/usr/bin/env python # encoding: utf-8 """ fuzz.py Copyright (c) 2011 Adam Cohen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import unicode_literals import platform import warnings try: from .StringMatcher import StringMatcher as SequenceMatcher except ImportError: if platform.python_implementation() != "PyPy": warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning') from difflib import SequenceMatcher from . import utils ########################### # Basic Scoring Functions # ########################### @utils.check_for_none @utils.check_empty_string def ratio(s1, s2): s1, s2 = utils.make_type_consistent(s1, s2) m = SequenceMatcher(None, s1, s2) return utils.intr(100 * m.ratio()) @utils.check_for_none @utils.check_empty_string def partial_ratio(s1, s2): """"Return the ratio of the most similar substring as a number between 0 and 100.""" s1, s2 = utils.make_type_consistent(s1, s2) if len(s1) <= len(s2): shorter = s1 longer = s2 else: shorter = s2 longer = s1 m = SequenceMatcher(None, shorter, longer) blocks = m.get_matching_blocks() # each block represents a sequence of matching characters in a string # of the form (idx_1, idx_2, len) # the best partial match will block align with at least one of those blocks # e.g. shorter = "abcd", longer = XXXbcdeEEE # block = (1,3,3) # best score === ratio("abcd", "Xbcd") scores = [] for block in blocks: long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0 long_end = long_start + len(shorter) long_substr = longer[long_start:long_end] m2 = SequenceMatcher(None, shorter, long_substr) r = m2.ratio() if r > .995: return 100 else: scores.append(r) return utils.intr(100 * max(scores)) ############################## # Advanced Scoring Functions # ############################## def _process_and_sort(s, force_ascii): """Return a cleaned string with token sorted.""" # pull tokens tokens = utils.full_process(s, force_ascii=force_ascii).split() # sort tokens and join sorted_string = u" ".join(sorted(tokens)) return sorted_string.strip() # Sorted Token # find all alphanumeric tokens in the string # sort those tokens and take ratio of resulting joined strings # controls for unordered string elements @utils.check_for_none def _token_sort(s1, s2, partial=True, force_ascii=True): sorted1 = _process_and_sort(s1, force_ascii) sorted2 = _process_and_sort(s2, force_ascii) if partial: return partial_ratio(sorted1, sorted2) else: return ratio(sorted1, sorted2) def token_sort_ratio(s1, s2, force_ascii=True): """Return a measure of the sequences' similarity between 0 and 100 but sorting the token before comparing. """ return _token_sort(s1, s2, partial=False, force_ascii=force_ascii) def partial_token_sort_ratio(s1, s2, force_ascii=True): """Return the ratio of the most similar substring as a number between 0 and 100 but sorting the token before comparing. """ return _token_sort(s1, s2, partial=True, force_ascii=force_ascii) @utils.check_for_none def _token_set(s1, s2, partial=True, force_ascii=True): """Find all alphanumeric tokens in each string... - treat them as a set - construct two strings of the form: - take ratios of those two strings - controls for unordered partial matches""" p1 = utils.full_process(s1, force_ascii=force_ascii) p2 = utils.full_process(s2, force_ascii=force_ascii) if not utils.validate_string(p1): return 0 if not utils.validate_string(p2): return 0 # pull tokens tokens1 = set(utils.full_process(p1).split()) tokens2 = set(utils.full_process(p2).split()) intersection = tokens1.intersection(tokens2) diff1to2 = tokens1.difference(tokens2) diff2to1 = tokens2.difference(tokens1) sorted_sect = " ".join(sorted(intersection)) sorted_1to2 = " ".join(sorted(diff1to2)) sorted_2to1 = " ".join(sorted(diff2to1)) combined_1to2 = sorted_sect + " " + sorted_1to2 combined_2to1 = sorted_sect + " " + sorted_2to1 # strip sorted_sect = sorted_sect.strip() combined_1to2 = combined_1to2.strip() combined_2to1 = combined_2to1.strip() if partial: ratio_func = partial_ratio else: ratio_func = ratio pairwise = [ ratio_func(sorted_sect, combined_1to2), ratio_func(sorted_sect, combined_2to1), ratio_func(combined_1to2, combined_2to1) ] return max(pairwise) def token_set_ratio(s1, s2, force_ascii=True): return _token_set(s1, s2, partial=False, force_ascii=force_ascii) def partial_token_set_ratio(s1, s2, force_ascii=True): return _token_set(s1, s2, partial=True, force_ascii=force_ascii) ################### # Combination API # ################### # q is for quick def QRatio(s1, s2, force_ascii=True): p1 = utils.full_process(s1, force_ascii=force_ascii) p2 = utils.full_process(s2, force_ascii=force_ascii) if not utils.validate_string(p1): return 0 if not utils.validate_string(p2): return 0 return ratio(p1, p2) def UQRatio(s1, s2): return QRatio(s1, s2, force_ascii=False) # w is for weighted def WRatio(s1, s2, force_ascii=True): """Return a measure of the sequences' similarity between 0 and 100, using different algorithms. """ p1 = utils.full_process(s1, force_ascii=force_ascii) p2 = utils.full_process(s2, force_ascii=force_ascii) if not utils.validate_string(p1): return 0 if not utils.validate_string(p2): return 0 # should we look at partials? try_partial = True unbase_scale = .95 partial_scale = .90 base = ratio(p1, p2) len_ratio = float(max(len(p1), len(p2))) / min(len(p1), len(p2)) # if strings are similar length, don't use partials if len_ratio < 1.5: try_partial = False # if one string is much much shorter than the other if len_ratio > 8: partial_scale = .6 if try_partial: partial = partial_ratio(p1, p2) * partial_scale ptsor = partial_token_sort_ratio(p1, p2, force_ascii=force_ascii) \ * unbase_scale * partial_scale ptser = partial_token_set_ratio(p1, p2, force_ascii=force_ascii) \ * unbase_scale * partial_scale return utils.intr(max(base, partial, ptsor, ptser)) else: tsor = token_sort_ratio(p1, p2, force_ascii=force_ascii) * unbase_scale tser = token_set_ratio(p1, p2, force_ascii=force_ascii) * unbase_scale return utils.intr(max(base, tsor, tser)) def UWRatio(s1, s2): """Return a measure of the sequences' similarity between 0 and 100, using different algorithms. Same as WRatio but preserving unicode. """ return WRatio(s1, s2, force_ascii=False) fuzzywuzzy-0.10.0/fuzzywuzzy/process.py0000644000076500000240000002112612622301336020543 0ustar josestaff00000000000000#!/usr/bin/env python # encoding: utf-8 """ process.py Copyright (c) 2011 Adam Cohen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import itertools from . import fuzz from . import utils def extract(query, choices, processor=None, scorer=None, limit=5): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a list of tuples containing the match and it's score. If a dictionary is used, also returns the key for each match. Arguments: query: An object representing the thing we want to find. choices: An iterable or dictionary-like object containing choices to be matched against the query. Dictionary arguments of {key: value} pairs will attempt to match the query against each value. processor: Optional function of the form f(a) -> b, where a is an individual choice and b is the choice to be used in matching. This can be used to match against, say, the first element of a list: lambda x: x[0] Defaults to fuzzywuzzy.utils.full_process(). scorer: Optional function for scoring matches between the query and an individual processed choice. This should be a function of the form f(query, choice) -> int. By default, fuzz.WRatio() is used and expects both query and choice to be strings. limit: Optional maximum for the number of elements returned. Defaults to 5. Returns: List of tuples containing the match and its score. If a list is used for choices, then the result will be 2-tuples. If a dictionary is used, then the result will be 3-tuples containing he key for each match. For example, searching for 'bird' in the dictionary {'bard': 'train', 'dog': 'man'} may return [('train', 22, 'bard'), ('man', 0, 'dog')] """ if choices is None: return [] # Catch generators without lengths try: if len(choices) == 0: return [] except TypeError: pass # default, turn whatever the choice is into a workable string if not processor: processor = utils.full_process # default: wratio if not scorer: scorer = fuzz.WRatio sl = [] try: # See if choices is a dictionary-like object. for key, choice in choices.items(): processed = processor(choice) score = scorer(query, processed) sl.append((choice, score, key)) except AttributeError: # It's a list; just iterate over it. for choice in choices: processed = processor(choice) score = scorer(query, processed) sl.append((choice, score)) sl.sort(key=lambda i: i[1], reverse=True) return sl[:limit] def extractBests(query, choices, processor=None, scorer=None, score_cutoff=0, limit=5): """Get a list of the best matches to a collection of choices. Convenience function for getting the choices with best scores. Args: query: A string to match against choices: A list or dictionary of choices, suitable for use with extract(). processor: Optional function for transforming choices before matching. See extract(). scorer: Scoring function for extract(). score_cutoff: Optional argument for score threshold. No matches with a score less than this number will be returned. Defaults to 0. limit: Optional maximum for the number of elements returned. Defaults to 5. Returns: A a list of (match, score) tuples. """ best_list = extract(query, choices, processor, scorer, limit) return list(itertools.takewhile(lambda x: x[1] >= score_cutoff, best_list)) def extractOne(query, choices, processor=None, scorer=None, score_cutoff=0): """Find the single best match above a score in a list of choices. This is a convenience method which returns the single best choice. See extract() for the full arguments list. Args: query: A string to match against choices: A list or dictionary of choices, suitable for use with extract(). processor: Optional function for transforming choices before matching. See extract(). scorer: Scoring function for extract(). score_cutoff: Optional argument for score threshold. If the best match is found, but it is not greater than this number, then return None anyway ("not a good enough match"). Defaults to 0. Returns: A tuple containing a single match and its score, if a match was found that was above score_cutoff. Otherwise, returns None. """ best_list = extract(query, choices, processor, scorer, limit=1) if len(best_list) > 0 and best_list[0][1] >= score_cutoff: return best_list[0] return None def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio): """This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify and remove duplicates. Specifically, it uses the process.extract to identify duplicates that score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list since we assume this item contains the most entity information and returns that. It breaks string length ties on an alphabetical sort. Note: as the threshold DECREASES the number of duplicates that are found INCREASES. This means that the returned deduplicated list will likely be shorter. Raise the threshold for fuzzy_dedupe to be less sensitive. Args: contains_dupes: A list of strings that we would like to dedupe. threshold: the numerical value (0,100) point at which we expect to find duplicates. Defaults to 70 out of 100 scorer: Optional function for scoring matches between the query and an individual processed choice. This should be a function of the form f(query, choice) -> int. By default, fuzz.token_set_ratio() is used and expects both query and choice to be strings. Returns: A deduplicated list. For example: In: contains_dupes = ['Frodo Baggin', 'Frodo Baggins', 'F. Baggins', 'Samwise G.', 'Gandalf', 'Bilbo Baggins'] In: fuzzy_dedupe(contains_dupes) Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf'] """ extractor = [] # iterate over items in *contains_dupes* for item in contains_dupes: # return all duplicate matches found matches = extract(item, contains_dupes, limit=None, scorer=scorer) # filter matches based on the threshold filtered = [x for x in matches if x[1] > threshold] # if there is only 1 item in *filtered*, no duplicates were found so append to *extracted* if len(filtered) == 1: extractor.append(filtered[0][0]) else: # alpha sort filtered = sorted(filtered, key=lambda x: x[0]) # length sort filter_sort = sorted(filtered, key=lambda x: len(x[0]), reverse=True) # take first item as our 'canonical example' extractor.append(filter_sort[0][0]) # uniquify *extractor* list keys = {} for e in extractor: keys[e] = 1 extractor = keys.keys() # check that extractor differs from contain_dupes (e.g. duplicates were found) # if not, then return the original list if len(extractor) == len(contains_dupes): return contains_dupes else: return extractor fuzzywuzzy-0.10.0/fuzzywuzzy/string_processing.py0000644000076500000240000000141412667340761022643 0ustar josestaff00000000000000from __future__ import unicode_literals import re import string import sys PY3 = sys.version_info[0] == 3 if PY3: string = str class StringProcessor(object): """ This class defines method to process strings in the most efficient way. Ideally all the methods below use unicode strings for both input and output. """ regex = re.compile(r"(?ui)\W") @classmethod def replace_non_letters_non_numbers_with_whitespace(cls, a_string): """ This function replaces any sequence of non letters and non numbers with a single white space. """ return cls.regex.sub(" ", a_string) strip = staticmethod(string.strip) to_lower_case = staticmethod(string.lower) to_upper_case = staticmethod(string.upper) fuzzywuzzy-0.10.0/fuzzywuzzy/StringMatcher.py0000644000076500000240000000445212561205360021644 0ustar josestaff00000000000000#!/usr/bin/env python # encoding: utf-8 """ StringMatcher.py ported from python-Levenshtein [https://github.com/miohtama/python-Levenshtein] """ from Levenshtein import * from warnings import warn class StringMatcher: """A SequenceMatcher-like class built on the top of Levenshtein""" def _reset_cache(self): self._ratio = self._distance = None self._opcodes = self._editops = self._matching_blocks = None def __init__(self, isjunk=None, seq1='', seq2=''): if isjunk: warn("isjunk not NOT implemented, it will be ignored") self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seqs(self, seq1, seq2): self._str1, self._str2 = seq1, seq2 self._reset_cache() def set_seq1(self, seq1): self._str1 = seq1 self._reset_cache() def set_seq2(self, seq2): self._str2 = seq2 self._reset_cache() def get_opcodes(self): if not self._opcodes: if self._editops: self._opcodes = opcodes(self._editops, self._str1, self._str2) else: self._opcodes = opcodes(self._str1, self._str2) return self._opcodes def get_editops(self): if not self._editops: if self._opcodes: self._editops = editops(self._opcodes, self._str1, self._str2) else: self._editops = editops(self._str1, self._str2) return self._editops def get_matching_blocks(self): if not self._matching_blocks: self._matching_blocks = matching_blocks(self.get_opcodes(), self._str1, self._str2) return self._matching_blocks def ratio(self): if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def quick_ratio(self): # This is usually quick enough :o) if not self._ratio: self._ratio = ratio(self._str1, self._str2) return self._ratio def real_quick_ratio(self): len1, len2 = len(self._str1), len(self._str2) return 2.0 * min(len1, len2) / (len1 + len2) def distance(self): if not self._distance: self._distance = distance(self._str1, self._str2) return self._distance fuzzywuzzy-0.10.0/fuzzywuzzy/utils.py0000644000076500000240000000437412671432454020245 0ustar josestaff00000000000000from __future__ import unicode_literals import sys import functools from fuzzywuzzy.string_processing import StringProcessor PY3 = sys.version_info[0] == 3 def validate_string(s): try: return len(s) > 0 except TypeError: return False def check_for_none(func): @functools.wraps(func) def decorator(*args, **kwargs): if args[0] is None or args[1] is None: return 0 return func(*args, **kwargs) return decorator def check_empty_string(func): @functools.wraps(func) def decorator(*args, **kwargs): if len(args[0]) == 0 or len(args[1]) == 0: return 0 return func(*args, **kwargs) return decorator bad_chars = str("").join([chr(i) for i in range(128, 256)]) # ascii dammit! if PY3: translation_table = dict((ord(c), None) for c in bad_chars) unicode = str def asciionly(s): if PY3: return s.translate(translation_table) else: return s.translate(None, bad_chars) def asciidammit(s): if type(s) is str: return asciionly(s) elif type(s) is unicode: return asciionly(s.encode('ascii', 'ignore')) else: return asciidammit(unicode(s)) def make_type_consistent(s1, s2): """If both objects aren't either both string or unicode instances force them to unicode""" if isinstance(s1, str) and isinstance(s2, str): return s1, s2 elif isinstance(s1, unicode) and isinstance(s2, unicode): return s1, s2 else: return unicode(s1), unicode(s2) def full_process(s, force_ascii=False): """Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case if force_ascii == True, force convert to ascii""" if s is None: return "" if force_ascii: s = asciidammit(s) # Keep only Letters and Numbers (see Unicode docs). string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s) # Force into lowercase. string_out = StringProcessor.to_lower_case(string_out) # Remove leading and trailing whitespaces. string_out = StringProcessor.strip(string_out) return string_out def intr(n): '''Returns a correctly rounded integer''' return int(round(n)) fuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/0000755000076500000240000000000012671432702020211 5ustar josestaff00000000000000fuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/dependency_links.txt0000644000076500000240000000000112671432702024257 0ustar josestaff00000000000000 fuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/pbr.json0000644000076500000240000000005612671432702021670 0ustar josestaff00000000000000{"is_release": true, "git_version": "6244ce3"}fuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/PKG-INFO0000644000076500000240000001141412671432702021307 0ustar josestaff00000000000000Metadata-Version: 1.1 Name: fuzzywuzzy Version: 0.10.0 Summary: Fuzzy string matching in python Home-page: https://github.com/seatgeek/fuzzywuzzy Author: Adam Cohen Author-email: adam@seatgeek.com License: Copyright (c) 2014 SeatGeek, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Description: |Build Status| FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to help calculate differences between sequences in a simple to use package. Requirements ============ - Python 2.4 or higher - difflib - python-Levenshtein (optional, provides a 4-10x speedup in String Matching) Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Adding to your ``requirements.txt`` file (run ``pip install -r requirements.txt`` afterwards) .. code:: bash git+ssh://git@github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Manually via GIT .. code:: bash git clone git://github.com/seatgeek/fuzzywuzzy.git fuzzywuzzy cd fuzzywuzzy python setup.py install Usage ===== .. code:: python >>> from fuzzywuzzy import fuzz >>> from fuzzywuzzy import process Simple Ratio ~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("this is a test", "this is a test!") 96 Partial Ratio ~~~~~~~~~~~~~ .. code:: python >>> fuzz.partial_ratio("this is a test", "this is a test!") 100 Token Sort Ratio ~~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 90 >>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 100 Token Set Ratio ~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 84 >>> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 100 Process ~~~~~~~ .. code:: python >>> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"] >>> process.extract("new york jets", choices, limit=2) [('New York Jets', 100), ('New York Giants', 78)] >>> process.extractOne("cowboys", choices) ("Dallas Cowboys", 90) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ Some people are porting FuzzyWuzzy to other languages. Here is one port we know about: - Java: https://github.com/WantedTechnologies/xpresso/wiki/Approximate-string-comparison-and-pattern-matching-in-Java Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 fuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/SOURCES.txt0000644000076500000240000000066412671432702022103 0ustar josestaff00000000000000CHANGES.rst LICENSE.txt MANIFEST.in README README.rst requirements.txt setup.py test_fuzzywuzzy.py fuzzywuzzy/StringMatcher.py fuzzywuzzy/__init__.py fuzzywuzzy/fuzz.py fuzzywuzzy/process.py fuzzywuzzy/string_processing.py fuzzywuzzy/utils.py fuzzywuzzy.egg-info/PKG-INFO fuzzywuzzy.egg-info/SOURCES.txt fuzzywuzzy.egg-info/dependency_links.txt fuzzywuzzy.egg-info/pbr.json fuzzywuzzy.egg-info/top_level.txt fuzzywuzzy.egg-info/zip-safefuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/top_level.txt0000644000076500000240000000001312671432702022735 0ustar josestaff00000000000000fuzzywuzzy fuzzywuzzy-0.10.0/fuzzywuzzy.egg-info/zip-safe0000644000076500000240000000000112464504455021646 0ustar josestaff00000000000000 fuzzywuzzy-0.10.0/LICENSE.txt0000644000076500000240000000204212457514572016030 0ustar josestaff00000000000000Copyright (c) 2014 SeatGeek, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. fuzzywuzzy-0.10.0/MANIFEST.in0000644000076500000240000000006712457514572015750 0ustar josestaff00000000000000include *.txt include *.rst include test_fuzzywuzzy.py fuzzywuzzy-0.10.0/PKG-INFO0000644000076500000240000001141412671432702015275 0ustar josestaff00000000000000Metadata-Version: 1.1 Name: fuzzywuzzy Version: 0.10.0 Summary: Fuzzy string matching in python Home-page: https://github.com/seatgeek/fuzzywuzzy Author: Adam Cohen Author-email: adam@seatgeek.com License: Copyright (c) 2014 SeatGeek, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Description: |Build Status| FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to help calculate differences between sequences in a simple to use package. Requirements ============ - Python 2.4 or higher - difflib - python-Levenshtein (optional, provides a 4-10x speedup in String Matching) Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Adding to your ``requirements.txt`` file (run ``pip install -r requirements.txt`` afterwards) .. code:: bash git+ssh://git@github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Manually via GIT .. code:: bash git clone git://github.com/seatgeek/fuzzywuzzy.git fuzzywuzzy cd fuzzywuzzy python setup.py install Usage ===== .. code:: python >>> from fuzzywuzzy import fuzz >>> from fuzzywuzzy import process Simple Ratio ~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("this is a test", "this is a test!") 96 Partial Ratio ~~~~~~~~~~~~~ .. code:: python >>> fuzz.partial_ratio("this is a test", "this is a test!") 100 Token Sort Ratio ~~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 90 >>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 100 Token Set Ratio ~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 84 >>> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 100 Process ~~~~~~~ .. code:: python >>> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"] >>> process.extract("new york jets", choices, limit=2) [('New York Jets', 100), ('New York Giants', 78)] >>> process.extractOne("cowboys", choices) ("Dallas Cowboys", 90) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ Some people are porting FuzzyWuzzy to other languages. Here is one port we know about: - Java: https://github.com/WantedTechnologies/xpresso/wiki/Approximate-string-comparison-and-pattern-matching-in-Java Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 fuzzywuzzy-0.10.0/README0000644000076500000240000000457612671432702015073 0ustar josestaff00000000000000|Build Status| FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to help calculate differences between sequences in a simple to use package. Requirements ============ - Python 2.4 or higher - difflib - python-Levenshtein (optional, provides a 4-10x speedup in String Matching) Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Adding to your ``requirements.txt`` file (run ``pip install -r requirements.txt`` afterwards) .. code:: bash git+ssh://git@github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Manually via GIT .. code:: bash git clone git://github.com/seatgeek/fuzzywuzzy.git fuzzywuzzy cd fuzzywuzzy python setup.py install Usage ===== .. code:: python >>> from fuzzywuzzy import fuzz >>> from fuzzywuzzy import process Simple Ratio ~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("this is a test", "this is a test!") 96 Partial Ratio ~~~~~~~~~~~~~ .. code:: python >>> fuzz.partial_ratio("this is a test", "this is a test!") 100 Token Sort Ratio ~~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 90 >>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 100 Token Set Ratio ~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 84 >>> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 100 Process ~~~~~~~ .. code:: python >>> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"] >>> process.extract("new york jets", choices, limit=2) [('New York Jets', 100), ('New York Giants', 78)] >>> process.extractOne("cowboys", choices) ("Dallas Cowboys", 90) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ Some people are porting FuzzyWuzzy to other languages. Here is one port we know about: - Java: https://github.com/WantedTechnologies/xpresso/wiki/Approximate-string-comparison-and-pattern-matching-in-Java fuzzywuzzy-0.10.0/README.rst0000644000076500000000000000457612671432677015710 0ustar josewheel00000000000000|Build Status| FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to help calculate differences between sequences in a simple to use package. Requirements ============ - Python 2.4 or higher - difflib - python-Levenshtein (optional, provides a 4-10x speedup in String Matching) Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Adding to your ``requirements.txt`` file (run ``pip install -r requirements.txt`` afterwards) .. code:: bash git+ssh://git@github.com/seatgeek/fuzzywuzzy.git@0.10.0#egg=fuzzywuzzy Manually via GIT .. code:: bash git clone git://github.com/seatgeek/fuzzywuzzy.git fuzzywuzzy cd fuzzywuzzy python setup.py install Usage ===== .. code:: python >>> from fuzzywuzzy import fuzz >>> from fuzzywuzzy import process Simple Ratio ~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("this is a test", "this is a test!") 96 Partial Ratio ~~~~~~~~~~~~~ .. code:: python >>> fuzz.partial_ratio("this is a test", "this is a test!") 100 Token Sort Ratio ~~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 90 >>> fuzz.token_sort_ratio("fuzzy wuzzy was a bear", "wuzzy fuzzy was a bear") 100 Token Set Ratio ~~~~~~~~~~~~~~~ .. code:: python >>> fuzz.token_sort_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 84 >>> fuzz.token_set_ratio("fuzzy was a bear", "fuzzy fuzzy was a bear") 100 Process ~~~~~~~ .. code:: python >>> choices = ["Atlanta Falcons", "New York Jets", "New York Giants", "Dallas Cowboys"] >>> process.extract("new york jets", choices, limit=2) [('New York Jets', 100), ('New York Giants', 78)] >>> process.extractOne("cowboys", choices) ("Dallas Cowboys", 90) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ Some people are porting FuzzyWuzzy to other languages. Here is one port we know about: - Java: https://github.com/WantedTechnologies/xpresso/wiki/Approximate-string-comparison-and-pattern-matching-in-Java fuzzywuzzy-0.10.0/requirements.txt0000644000076500000240000000000012457514572017461 0ustar josestaff00000000000000fuzzywuzzy-0.10.0/setup.cfg0000644000076500000240000000007312671432702016020 0ustar josestaff00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 fuzzywuzzy-0.10.0/setup.py0000644000076500000240000000176112561205167015717 0ustar josestaff00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014 SeatGeek # This file is part of fuzzywuzzy. from fuzzywuzzy import __version__ import os try: from setuptools import setup except ImportError: from distutils.core import setup def open_file(fname): return open(os.path.join(os.path.dirname(__file__), fname)) setup( name='fuzzywuzzy', version=__version__, author='Adam Cohen', author_email='adam@seatgeek.com', packages=['fuzzywuzzy'], url='https://github.com/seatgeek/fuzzywuzzy', license=open('LICENSE.txt').read(), classifiers=[ 'Intended Audience :: Developers', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3' ], description='Fuzzy string matching in python', long_description=open_file('README.rst').read(), zip_safe=True, ) fuzzywuzzy-0.10.0/test_fuzzywuzzy.py0000644000076500000240000004156312671432454020145 0ustar josestaff00000000000000# -*- coding: utf8 -*- from __future__ import unicode_literals import unittest import re import sys import pep8 from fuzzywuzzy import fuzz from fuzzywuzzy import process from fuzzywuzzy import utils from fuzzywuzzy.string_processing import StringProcessor if sys.version_info[0] == 3: unicode = str if sys.version_info[:2] == (2, 6): # Monkeypatch to make tests work on 2.6 def assertLess(first, second, msg=None): assert first > second unittest.TestCase.assertLess = assertLess class StringProcessingTest(unittest.TestCase): def test_replace_non_letters_non_numbers_with_whitespace(self): strings = ["new york mets - atlanta braves", "Cães danados", "New York //// Mets $$$", "Ça va?"] for string in strings: proc_string = StringProcessor.replace_non_letters_non_numbers_with_whitespace(string) regex = re.compile(r"(?ui)[\W]") for expr in regex.finditer(proc_string): self.assertEqual(expr.group(), " ") def test_dont_condense_whitespace(self): s1 = "new york mets - atlanta braves" s2 = "new york mets atlanta braves" p1 = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s1) p2 = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s2) self.assertNotEqual(p1, p2) class UtilsTest(unittest.TestCase): def setUp(self): self.s1 = "new york mets" self.s1a = "new york mets" self.s2 = "new YORK mets" self.s3 = "the wonderful new york mets" self.s4 = "new york mets vs atlanta braves" self.s5 = "atlanta braves vs new york mets" self.s6 = "new york mets - atlanta braves" self.mixed_strings = [ "Lorem Ipsum is simply dummy text of the printing and typesetting industry.", "C'est la vie", "Ça va?", "Cães danados", "\xacCamarões assados", "a\xac\u1234\u20ac\U00008000", "\u00C1" ] def tearDown(self): pass def test_asciidammit(self): for s in self.mixed_strings: utils.asciidammit(s) def test_asciionly(self): for s in self.mixed_strings: # ascii only only runs on strings s = utils.asciidammit(s) utils.asciionly(s) def test_fullProcess(self): for s in self.mixed_strings: utils.full_process(s) def test_fullProcessForceAscii(self): for s in self.mixed_strings: utils.full_process(s, force_ascii=True) class RatioTest(unittest.TestCase): def setUp(self): self.s1 = "new york mets" self.s1a = "new york mets" self.s2 = "new YORK mets" self.s3 = "the wonderful new york mets" self.s4 = "new york mets vs atlanta braves" self.s5 = "atlanta braves vs new york mets" self.s6 = "new york mets - atlanta braves" self.s7 = 'new york city mets - atlanta braves' self.cirque_strings = [ "cirque du soleil - zarkana - las vegas", "cirque du soleil ", "cirque du soleil las vegas", "zarkana las vegas", "las vegas cirque du soleil at the bellagio", "zarakana - cirque du soleil - bellagio" ] self.baseball_strings = [ "new york mets vs chicago cubs", "chicago cubs vs chicago white sox", "philladelphia phillies vs atlanta braves", "braves vs mets", ] def tearDown(self): pass def testEqual(self): self.assertEqual(fuzz.ratio(self.s1, self.s1a), 100) def testCaseInsensitive(self): self.assertNotEqual(fuzz.ratio(self.s1, self.s2), 100) self.assertEqual(fuzz.ratio(utils.full_process(self.s1), utils.full_process(self.s2)), 100) def testPartialRatio(self): self.assertEqual(fuzz.partial_ratio(self.s1, self.s3), 100) def testTokenSortRatio(self): self.assertEqual(fuzz.token_sort_ratio(self.s1, self.s1a), 100) def testPartialTokenSortRatio(self): self.assertEqual(fuzz.partial_token_sort_ratio(self.s1, self.s1a), 100) self.assertEqual(fuzz.partial_token_sort_ratio(self.s4, self.s5), 100) def testTokenSetRatio(self): self.assertEqual(fuzz.token_set_ratio(self.s4, self.s5), 100) def testPartialTokenSetRatio(self): self.assertEqual(fuzz.partial_token_set_ratio(self.s4, self.s7), 100) def testQuickRatioEqual(self): self.assertEqual(fuzz.QRatio(self.s1, self.s1a), 100) def testQuickRatioCaseInsensitive(self): self.assertEqual(fuzz.QRatio(self.s1, self.s2), 100) def testQuickRatioNotEqual(self): self.assertNotEqual(fuzz.QRatio(self.s1, self.s3), 100) def testWRatioEqual(self): self.assertEqual(fuzz.WRatio(self.s1, self.s1a), 100) def testWRatioCaseInsensitive(self): self.assertEqual(fuzz.WRatio(self.s1, self.s2), 100) def testWRatioPartialMatch(self): # a partial match is scaled by .9 self.assertEqual(fuzz.WRatio(self.s1, self.s3), 90) def testWRatioMisorderedMatch(self): # misordered full matches are scaled by .95 self.assertEqual(fuzz.WRatio(self.s4, self.s5), 95) def testWRatioUnicode(self): self.assertEqual(fuzz.WRatio(unicode(self.s1), unicode(self.s1a)), 100) def testQRatioUnicode(self): self.assertEqual(fuzz.WRatio(unicode(self.s1), unicode(self.s1a)), 100) def testEmptyStringsScore0(self): self.assertEqual(fuzz.ratio("", ""), 0) self.assertEqual(fuzz.partial_ratio("", ""), 0) def testIssueSeven(self): s1 = "HSINCHUANG" s2 = "SINJHUAN" s3 = "LSINJHUANG DISTRIC" s4 = "SINJHUANG DISTRICT" self.assertTrue(fuzz.partial_ratio(s1, s2) > 75) self.assertTrue(fuzz.partial_ratio(s1, s3) > 75) self.assertTrue(fuzz.partial_ratio(s1, s4) > 75) def testRatioUnicodeString(self): s1 = "\u00C1" s2 = "ABCD" score = fuzz.ratio(s1, s2) self.assertEqual(0, score) def testPartialRatioUnicodeString(self): s1 = "\u00C1" s2 = "ABCD" score = fuzz.partial_ratio(s1, s2) self.assertEqual(0, score) def testWRatioUnicodeString(self): s1 = "\u00C1" s2 = "ABCD" score = fuzz.WRatio(s1, s2) self.assertEqual(0, score) # Cyrillic. s1 = "\u043f\u0441\u0438\u0445\u043e\u043b\u043e\u0433" s2 = "\u043f\u0441\u0438\u0445\u043e\u0442\u0435\u0440\u0430\u043f\u0435\u0432\u0442" score = fuzz.WRatio(s1, s2, force_ascii=False) self.assertNotEqual(0, score) # Chinese. s1 = "\u6211\u4e86\u89e3\u6570\u5b66" s2 = "\u6211\u5b66\u6570\u5b66" score = fuzz.WRatio(s1, s2, force_ascii=False) self.assertNotEqual(0, score) def testQRatioUnicodeString(self): s1 = "\u00C1" s2 = "ABCD" score = fuzz.QRatio(s1, s2) self.assertEqual(0, score) # Cyrillic. s1 = "\u043f\u0441\u0438\u0445\u043e\u043b\u043e\u0433" s2 = "\u043f\u0441\u0438\u0445\u043e\u0442\u0435\u0440\u0430\u043f\u0435\u0432\u0442" score = fuzz.QRatio(s1, s2, force_ascii=False) self.assertNotEqual(0, score) # Chinese. s1 = "\u6211\u4e86\u89e3\u6570\u5b66" s2 = "\u6211\u5b66\u6570\u5b66" score = fuzz.QRatio(s1, s2, force_ascii=False) self.assertNotEqual(0, score) def testQratioForceAscii(self): s1 = "ABCD\u00C1" s2 = "ABCD" score = fuzz.QRatio(s1, s2, force_ascii=True) self.assertEqual(score, 100) score = fuzz.QRatio(s1, s2, force_ascii=False) self.assertLess(score, 100) def testQRatioForceAscii(self): s1 = "ABCD\u00C1" s2 = "ABCD" score = fuzz.WRatio(s1, s2, force_ascii=True) self.assertEqual(score, 100) score = fuzz.WRatio(s1, s2, force_ascii=False) self.assertLess(score, 100) def testTokenSetForceAscii(self): s1 = "ABCD\u00C1 HELP\u00C1" s2 = "ABCD HELP" score = fuzz._token_set(s1, s2, force_ascii=True) self.assertEqual(score, 100) score = fuzz._token_set(s1, s2, force_ascii=False) self.assertLess(score, 100) def testTokenSortForceAscii(self): s1 = "ABCD\u00C1 HELP\u00C1" s2 = "ABCD HELP" score = fuzz._token_sort(s1, s2, force_ascii=True) self.assertEqual(score, 100) score = fuzz._token_sort(s1, s2, force_ascii=False) self.assertLess(score, 100) class ValidatorTest(unittest.TestCase): def setUp(self): self.testFunc = lambda *args, **kwargs: (args, kwargs) def testCheckForNone(self): invalid_input = [ (None, None), ('Some', None), (None, 'Some') ] decorated_func = utils.check_for_none(self.testFunc) for i in invalid_input: self.assertEqual(decorated_func(*i), 0) valid_input = ('Some', 'Some') actual = decorated_func(*valid_input) self.assertNotEqual(actual, 0) def testCheckEmptyString(self): invalid_input = [ ('', ''), ('Some', ''), ('', 'Some') ] decorated_func = utils.check_empty_string(self.testFunc) for i in invalid_input: self.assertEqual(decorated_func(*i), 0) valid_input = ('Some', 'Some') actual = decorated_func(*valid_input) self.assertNotEqual(actual, 0) class ProcessTest(unittest.TestCase): def setUp(self): self.s1 = "new york mets" self.s1a = "new york mets" self.s2 = "new YORK mets" self.s3 = "the wonderful new york mets" self.s4 = "new york mets vs atlanta braves" self.s5 = "atlanta braves vs new york mets" self.s6 = "new york mets - atlanta braves" self.cirque_strings = [ "cirque du soleil - zarkana - las vegas", "cirque du soleil ", "cirque du soleil las vegas", "zarkana las vegas", "las vegas cirque du soleil at the bellagio", "zarakana - cirque du soleil - bellagio" ] self.baseball_strings = [ "new york mets vs chicago cubs", "chicago cubs vs chicago white sox", "philladelphia phillies vs atlanta braves", "braves vs mets", ] def testGetBestChoice1(self): query = "new york mets at atlanta braves" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], "braves vs mets") def testGetBestChoice2(self): query = "philadelphia phillies at atlanta braves" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], self.baseball_strings[2]) def testGetBestChoice3(self): query = "atlanta braves at philadelphia phillies" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], self.baseball_strings[2]) def testGetBestChoice4(self): query = "chicago cubs vs new york mets" best = process.extractOne(query, self.baseball_strings) self.assertEqual(best[0], self.baseball_strings[0]) def testWithProcessor(self): events = [ ["chicago cubs vs new york mets", "CitiField", "2011-05-11", "8pm"], ["new york yankees vs boston red sox", "Fenway Park", "2011-05-11", "8pm"], ["atlanta braves vs pittsburgh pirates", "PNC Park", "2011-05-11", "8pm"], ] query = "new york mets vs chicago cubs" best = process.extractOne(query, events, processor=lambda event: event[0]) self.assertEqual(best[0], events[0]) def testWithScorer(self): choices = [ "new york mets vs chicago cubs", "chicago cubs at new york mets", "atlanta braves vs pittsbugh pirates", "new york yankees vs boston red sox" ] choices_dict = { 1: "new york mets vs chicago cubs", 2: "chicago cubs vs chicago white sox", 3: "philladelphia phillies vs atlanta braves", 4: "braves vs mets" } # in this hypothetical example we care about ordering, so we use quick ratio query = "new york mets at chicago cubs" scorer = fuzz.QRatio # first, as an example, the normal way would select the "more # 'complete' match of choices[1]" best = process.extractOne(query, choices) self.assertEqual(best[0], choices[1]) # now, use the custom scorer best = process.extractOne(query, choices, scorer=scorer) self.assertEqual(best[0], choices[0]) best = process.extractOne(query, choices_dict) self.assertEqual(best[0], choices_dict[1]) def testWithCutoff(self): choices = [ "new york mets vs chicago cubs", "chicago cubs at new york mets", "atlanta braves vs pittsbugh pirates", "new york yankees vs boston red sox" ] query = "los angeles dodgers vs san francisco giants" # in this situation, this is an event that does not exist in the list # we don't want to randomly match to something, so we use a reasonable cutoff best = process.extractOne(query, choices, score_cutoff=50) self.assertTrue(best is None) # self.assertIsNone(best) # unittest.TestCase did not have assertIsNone until Python 2.7 # however if we had no cutoff, something would get returned # best = process.extractOne(query, choices) # self.assertIsNotNone(best) def testWithCutoff2(self): choices = [ "new york mets vs chicago cubs", "chicago cubs at new york mets", "atlanta braves vs pittsbugh pirates", "new york yankees vs boston red sox" ] query = "new york mets vs chicago cubs" # Only find 100-score cases res = process.extractOne(query, choices, score_cutoff=100) self.assertTrue(res is not None) best_match, score = res self.assertTrue(best_match is choices[0]) def testEmptyStrings(self): choices = [ "", "new york mets vs chicago cubs", "new york yankees vs boston red sox", "", "" ] query = "new york mets at chicago cubs" best = process.extractOne(query, choices) self.assertEqual(best[0], choices[1]) def testNullStrings(self): choices = [ None, "new york mets vs chicago cubs", "new york yankees vs boston red sox", None, None ] query = "new york mets at chicago cubs" best = process.extractOne(query, choices) self.assertEqual(best[0], choices[1]) def test_list_like_extract(self): """We should be able to use a list-like object for choices.""" def generate_choices(): choices = ['a', 'Bb', 'CcC'] for choice in choices: yield choice search = 'aaa' result = [(value, confidence) for value, confidence in process.extract(search, generate_choices())] self.assertTrue(len(result) > 0) def test_dict_like_extract(self): """We should be able to use a dict-like object for choices, not only a dict, and still get dict-like output. """ try: from UserDict import UserDict except ImportError: from collections import UserDict choices = UserDict({'aa': 'bb', 'a1': None}) search = 'aaa' result = process.extract(search, choices) self.assertTrue(len(result) > 0) for value, confidence, key in result: self.assertTrue(value in choices.values()) def test_dedupe(self): """We should be able to use a list-like object for contains_dupes """ # Test 1 contains_dupes = ['Frodo Baggins', 'Tom Sawyer', 'Bilbo Baggin', 'Samuel L. Jackson', 'F. Baggins', 'Frody Baggins', 'Bilbo Baggins'] result = process.dedupe(contains_dupes) self.assertTrue(len(result) < len(contains_dupes)) # Test 2 contains_dupes = ['Tom', 'Dick', 'Harry'] # we should end up with the same list since no duplicates are contained in the list (e.g. original list is returned) deduped_list = ['Tom', 'Dick', 'Harry'] result = process.dedupe(contains_dupes) self.assertEqual(result, deduped_list) class TestCodeFormat(unittest.TestCase): def test_pep8_conformance(self): pep8style = pep8.StyleGuide(quiet=True) pep8style.options.ignore = pep8style.options.ignore + tuple(['E501']) pep8style.input_dir('fuzzywuzzy') result = pep8style.check_files() self.assertEqual(result.total_errors, 0, "PEP8 POLICE - WOOOOOWOOOOOOOOOO") if __name__ == '__main__': unittest.main() # run all tests