fuzzywuzzy-0.18.0/0000755000076600000240000000000013621334452015224 5ustar garethtanstaff00000000000000fuzzywuzzy-0.18.0/PKG-INFO0000644000076600000240000001356113621334452016327 0ustar garethtanstaff00000000000000Metadata-Version: 2.1 Name: fuzzywuzzy Version: 0.18.0 Summary: Fuzzy string matching in python Home-page: https://github.com/seatgeek/fuzzywuzzy Author: Adam Cohen Author-email: adam@seatgeek.com License: GPLv2 Description: .. image:: https://travis-ci.org/seatgeek/fuzzywuzzy.svg?branch=master :target: https://travis-ci.org/seatgeek/fuzzywuzzy FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to calculate the differences between sequences in a simple-to-use package. Requirements ============ - Python 2.7 or higher - difflib - `python-Levenshtein `_ (optional, provides a 4-10x speedup in String Matching, though may result in `differing results for certain cases `_) For testing ~~~~~~~~~~~ - pycodestyle - hypothesis - pytest Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy or the following to install `python-Levenshtein` too .. code:: bash pip install fuzzywuzzy[speedup] Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.18.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.18.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!") 97 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") 91 >>> 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) You can also pass additional parameters to ``extractOne`` method to make it use a specific scorer. A typical use case is to match file paths: .. code:: python >>> process.extractOne("System of a down - Hypnotize - Heroin", songs) ('/music/library/good/System of a Down/2005 - Hypnotize/01 - Attack.mp3', 86) >>> process.extractOne("System of a down - Hypnotize - Heroin", songs, scorer=fuzz.token_sort_ratio) ("/music/library/good/System of a Down/2005 - Hypnotize/10 - She's Like Heroin.mp3", 61) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ FuzzyWuzzy is being ported to other languages too! Here are a few ports we know about: - Java: `xpresso's fuzzywuzzy implementation `_ - Java: `fuzzywuzzy (java port) `_ - Rust: `fuzzyrusty (Rust port) `_ - JavaScript: `fuzzball.js (JavaScript port) `_ - C++: `Tmplt/fuzzywuzzy `_ - C#: `fuzzysharp (.Net port) `_ - Go: `go-fuzzywuzz (Go port) `_ - Free Pascal: `FuzzyWuzzy.pas (Free Pascal port) `_ - Kotlin multiplatform: `FuzzyWuzzy-Kotlin `_ - R: `fuzzywuzzyR (R port) `_ Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v2 (GPLv2) Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Provides-Extra: speedup fuzzywuzzy-0.18.0/fuzzywuzzy/0000755000076600000240000000000013621334452017544 5ustar garethtanstaff00000000000000fuzzywuzzy-0.18.0/fuzzywuzzy/StringMatcher.py0000644000076600000240000000460512756767437022722 0ustar garethtanstaff00000000000000#!/usr/bin/env python # encoding: utf-8 """ StringMatcher.py ported from python-Levenshtein [https://github.com/miohtama/python-Levenshtein] License available here: https://github.com/miohtama/python-Levenshtein/blob/master/COPYING """ 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.18.0/fuzzywuzzy/__init__.py0000600000076600000240000000005713621334445021651 0ustar garethtanstaff00000000000000# -*- coding: utf-8 -*- __version__ = '0.18.0' fuzzywuzzy-0.18.0/fuzzywuzzy/string_processing.py0000644000076600000240000000141412756767270023700 0ustar garethtanstaff00000000000000from __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.18.0/fuzzywuzzy/utils.py0000644000076600000240000000504313562561512021263 0ustar garethtanstaff00000000000000from __future__ import unicode_literals import sys import functools from fuzzywuzzy.string_processing import StringProcessor PY3 = sys.version_info[0] == 3 def validate_string(s): """ Check input has length and that length > 0 :param s: :return: True if len(s) > 0 else False """ try: return len(s) > 0 except TypeError: return False def check_for_equivalence(func): @functools.wraps(func) def decorator(*args, **kwargs): if args[0] == args[1]: return 100 return func(*args, **kwargs) return decorator 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 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.18.0/fuzzywuzzy/process.py0000644000076600000240000002633113621333013021571 0ustar garethtanstaff00000000000000#!/usr/bin/env python # encoding: utf-8 from . import fuzz from . import utils import heapq import logging from functools import partial default_scorer = fuzz.WRatio default_processor = utils.full_process def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0): """Select the best match in a list or dictionary of choices. Find best matches in a list or dictionary of choices, return a generator of tuples containing the match and its 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 the query or 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. score_cutoff: Optional argument for score threshold. No matches with a score less than this number will be returned. Defaults to 0. Returns: Generator 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 the key for each match. For example, searching for 'bird' in the dictionary {'bard': 'train', 'dog': 'man'} may return ('train', 22, 'bard'), ('man', 0, 'dog') """ # Catch generators without lengths def no_process(x): return x try: if choices is None or len(choices) == 0: return except TypeError: pass # If the processor was removed by setting it to None # perfom a noop as it still needs to be a function if processor is None: processor = no_process # Run the processor on the input query. processed_query = processor(query) if len(processed_query) == 0: logging.warning(u"Applied processor reduces input query to empty string, " "all comparisons will have score 0. " "[Query: \'{0}\']".format(query)) # Don't run full_process twice if scorer in [fuzz.WRatio, fuzz.QRatio, fuzz.token_set_ratio, fuzz.token_sort_ratio, fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio, fuzz.UWRatio, fuzz.UQRatio] \ and processor == utils.full_process: processor = no_process # Only process the query once instead of for every choice if scorer in [fuzz.UWRatio, fuzz.UQRatio]: pre_processor = partial(utils.full_process, force_ascii=False) scorer = partial(scorer, full_process=False) elif scorer in [fuzz.WRatio, fuzz.QRatio, fuzz.token_set_ratio, fuzz.token_sort_ratio, fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio]: pre_processor = partial(utils.full_process, force_ascii=True) scorer = partial(scorer, full_process=False) else: pre_processor = no_process processed_query = pre_processor(processed_query) try: # See if choices is a dictionary-like object. for key, choice in choices.items(): processed = pre_processor(processor(choice)) score = scorer(processed_query, processed) if score >= score_cutoff: yield (choice, score, key) except AttributeError: # It's a list; just iterate over it. for choice in choices: processed = pre_processor(processor(choice)) score = scorer(processed_query, processed) if score >= score_cutoff: yield (choice, score) def extract(query, choices, processor=default_processor, scorer=default_scorer, 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 its 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 the query or 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 the key for each match. For example, searching for 'bird' in the dictionary {'bard': 'train', 'dog': 'man'} may return [('train', 22, 'bard'), ('man', 0, 'dog')] """ sl = extractWithoutOrder(query, choices, processor, scorer) return heapq.nlargest(limit, sl, key=lambda i: i[1]) if limit is not None else \ sorted(sl, key=lambda i: i[1], reverse=True) def extractBests(query, choices, processor=default_processor, scorer=default_scorer, 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 = extractWithoutOrder(query, choices, processor, scorer, score_cutoff) return heapq.nlargest(limit, best_list, key=lambda i: i[1]) if limit is not None else \ sorted(best_list, key=lambda i: i[1], reverse=True) def extractOne(query, choices, processor=default_processor, scorer=default_scorer, 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 = extractWithoutOrder(query, choices, processor, scorer, score_cutoff) try: return max(best_list, key=lambda i: i[1]) except ValueError: 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.18.0/fuzzywuzzy/fuzz.py0000644000076600000240000002256713562561512021133 0ustar garethtanstaff00000000000000#!/usr/bin/env python # encoding: utf-8 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_for_equivalence @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_for_equivalence @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, full_process=True): """Return a cleaned string with token sorted.""" # pull tokens ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s tokens = ts.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, full_process=True): sorted1 = _process_and_sort(s1, force_ascii, full_process=full_process) sorted2 = _process_and_sort(s2, force_ascii, full_process=full_process) if partial: return partial_ratio(sorted1, sorted2) else: return ratio(sorted1, sorted2) def token_sort_ratio(s1, s2, force_ascii=True, full_process=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, full_process=full_process) def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=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, full_process=full_process) @utils.check_for_none def _token_set(s1, s2, partial=True, force_ascii=True, full_process=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""" if not full_process and s1 == s2: return 100 p1 = utils.full_process(s1, force_ascii=force_ascii) if full_process else s1 p2 = utils.full_process(s2, force_ascii=force_ascii) if full_process else s2 if not utils.validate_string(p1): return 0 if not utils.validate_string(p2): return 0 # pull tokens tokens1 = set(p1.split()) tokens2 = set(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, full_process=True): return _token_set(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process) def partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True): return _token_set(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process) ################### # Combination API # ################### # q is for quick def QRatio(s1, s2, force_ascii=True, full_process=True): """ Quick ratio comparison between two strings. Runs full_process from utils on both strings Short circuits if either of the strings is empty after processing. :param s1: :param s2: :param force_ascii: Allow only ASCII characters (Default: True) :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True) :return: similarity ratio """ if full_process: p1 = utils.full_process(s1, force_ascii=force_ascii) p2 = utils.full_process(s2, force_ascii=force_ascii) else: p1 = s1 p2 = s2 if not utils.validate_string(p1): return 0 if not utils.validate_string(p2): return 0 return ratio(p1, p2) def UQRatio(s1, s2, full_process=True): """ Unicode quick ratio Calls QRatio with force_ascii set to False :param s1: :param s2: :return: similarity ratio """ return QRatio(s1, s2, force_ascii=False, full_process=full_process) # w is for weighted def WRatio(s1, s2, force_ascii=True, full_process=True): """ Return a measure of the sequences' similarity between 0 and 100, using different algorithms. **Steps in the order they occur** #. Run full_process from utils on both strings #. Short circuit if this makes either string empty #. Take the ratio of the two processed strings (fuzz.ratio) #. Run checks to compare the length of the strings * If one of the strings is more than 1.5 times as long as the other use partial_ratio comparisons - scale partial results by 0.9 (this makes sure only full results can return 100) * If one of the strings is over 8 times as long as the other instead scale by 0.6 #. Run the other ratio functions * if using partial ratio functions call partial_ratio, partial_token_sort_ratio and partial_token_set_ratio scale all of these by the ratio based on length * otherwise call token_sort_ratio and token_set_ratio * all token based comparisons are scaled by 0.95 (on top of any partial scalars) #. Take the highest value from these results round it and return it as an integer. :param s1: :param s2: :param force_ascii: Allow only ascii characters :type force_ascii: bool :full_process: Process inputs, used here to avoid double processing in extract functions (Default: True) :return: """ if full_process: p1 = utils.full_process(s1, force_ascii=force_ascii) p2 = utils.full_process(s2, force_ascii=force_ascii) else: p1 = s1 p2 = s2 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, full_process=False) \ * unbase_scale * partial_scale ptser = partial_token_set_ratio(p1, p2, full_process=False) \ * unbase_scale * partial_scale return utils.intr(max(base, partial, ptsor, ptser)) else: tsor = token_sort_ratio(p1, p2, full_process=False) * unbase_scale tser = token_set_ratio(p1, p2, full_process=False) * unbase_scale return utils.intr(max(base, tsor, tser)) def UWRatio(s1, s2, full_process=True): """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, full_process=full_process) fuzzywuzzy-0.18.0/MANIFEST.in0000644000076600000240000000006712756767270017005 0ustar garethtanstaff00000000000000include *.txt include *.rst include test_fuzzywuzzy.py fuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/0000755000076600000240000000000013621334452021236 5ustar garethtanstaff00000000000000fuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/PKG-INFO0000644000076600000240000001356113621334452022341 0ustar garethtanstaff00000000000000Metadata-Version: 2.1 Name: fuzzywuzzy Version: 0.18.0 Summary: Fuzzy string matching in python Home-page: https://github.com/seatgeek/fuzzywuzzy Author: Adam Cohen Author-email: adam@seatgeek.com License: GPLv2 Description: .. image:: https://travis-ci.org/seatgeek/fuzzywuzzy.svg?branch=master :target: https://travis-ci.org/seatgeek/fuzzywuzzy FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to calculate the differences between sequences in a simple-to-use package. Requirements ============ - Python 2.7 or higher - difflib - `python-Levenshtein `_ (optional, provides a 4-10x speedup in String Matching, though may result in `differing results for certain cases `_) For testing ~~~~~~~~~~~ - pycodestyle - hypothesis - pytest Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy or the following to install `python-Levenshtein` too .. code:: bash pip install fuzzywuzzy[speedup] Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.18.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.18.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!") 97 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") 91 >>> 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) You can also pass additional parameters to ``extractOne`` method to make it use a specific scorer. A typical use case is to match file paths: .. code:: python >>> process.extractOne("System of a down - Hypnotize - Heroin", songs) ('/music/library/good/System of a Down/2005 - Hypnotize/01 - Attack.mp3', 86) >>> process.extractOne("System of a down - Hypnotize - Heroin", songs, scorer=fuzz.token_sort_ratio) ("/music/library/good/System of a Down/2005 - Hypnotize/10 - She's Like Heroin.mp3", 61) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ FuzzyWuzzy is being ported to other languages too! Here are a few ports we know about: - Java: `xpresso's fuzzywuzzy implementation `_ - Java: `fuzzywuzzy (java port) `_ - Rust: `fuzzyrusty (Rust port) `_ - JavaScript: `fuzzball.js (JavaScript port) `_ - C++: `Tmplt/fuzzywuzzy `_ - C#: `fuzzysharp (.Net port) `_ - Go: `go-fuzzywuzz (Go port) `_ - Free Pascal: `FuzzyWuzzy.pas (Free Pascal port) `_ - Kotlin multiplatform: `FuzzyWuzzy-Kotlin `_ - R: `fuzzywuzzyR (R port) `_ Platform: UNKNOWN Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: GNU General Public License v2 (GPLv2) Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Provides-Extra: speedup fuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/zip-safe0000644000076600000240000000000113621334452022666 0ustar garethtanstaff00000000000000 fuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/SOURCES.txt0000644000076600000240000000066113621334452023125 0ustar garethtanstaff00000000000000CHANGES.rst LICENSE.txt MANIFEST.in README README.rst setup.cfg 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/requires.txt fuzzywuzzy.egg-info/top_level.txt fuzzywuzzy.egg-info/zip-safefuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/requires.txt0000644000076600000240000000004413621334452023634 0ustar garethtanstaff00000000000000 [speedup] python-levenshtein>=0.12 fuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/top_level.txt0000644000076600000240000000001313621334452023762 0ustar garethtanstaff00000000000000fuzzywuzzy fuzzywuzzy-0.18.0/fuzzywuzzy.egg-info/dependency_links.txt0000644000076600000240000000000113621334452025304 0ustar garethtanstaff00000000000000 fuzzywuzzy-0.18.0/README0000644000076600000240000001014113621334452016101 0ustar garethtanstaff00000000000000.. image:: https://travis-ci.org/seatgeek/fuzzywuzzy.svg?branch=master :target: https://travis-ci.org/seatgeek/fuzzywuzzy FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to calculate the differences between sequences in a simple-to-use package. Requirements ============ - Python 2.7 or higher - difflib - `python-Levenshtein `_ (optional, provides a 4-10x speedup in String Matching, though may result in `differing results for certain cases `_) For testing ~~~~~~~~~~~ - pycodestyle - hypothesis - pytest Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy or the following to install `python-Levenshtein` too .. code:: bash pip install fuzzywuzzy[speedup] Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.18.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.18.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!") 97 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") 91 >>> 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) You can also pass additional parameters to ``extractOne`` method to make it use a specific scorer. A typical use case is to match file paths: .. code:: python >>> process.extractOne("System of a down - Hypnotize - Heroin", songs) ('/music/library/good/System of a Down/2005 - Hypnotize/01 - Attack.mp3', 86) >>> process.extractOne("System of a down - Hypnotize - Heroin", songs, scorer=fuzz.token_sort_ratio) ("/music/library/good/System of a Down/2005 - Hypnotize/10 - She's Like Heroin.mp3", 61) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ FuzzyWuzzy is being ported to other languages too! Here are a few ports we know about: - Java: `xpresso's fuzzywuzzy implementation `_ - Java: `fuzzywuzzy (java port) `_ - Rust: `fuzzyrusty (Rust port) `_ - JavaScript: `fuzzball.js (JavaScript port) `_ - C++: `Tmplt/fuzzywuzzy `_ - C#: `fuzzysharp (.Net port) `_ - Go: `go-fuzzywuzz (Go port) `_ - Free Pascal: `FuzzyWuzzy.pas (Free Pascal port) `_ - Kotlin multiplatform: `FuzzyWuzzy-Kotlin `_ - R: `fuzzywuzzyR (R port) `_ fuzzywuzzy-0.18.0/setup.py0000644000076600000240000000223213621333013016725 0ustar garethtanstaff00000000000000#!/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'], extras_require={'speedup': ['python-levenshtein>=0.12']}, url='https://github.com/seatgeek/fuzzywuzzy', license="GPLv2", classifiers=[ 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], description='Fuzzy string matching in python', long_description=open_file('README.rst').read(), zip_safe=True, ) fuzzywuzzy-0.18.0/setup.cfg0000644000076600000240000000010313621334452017037 0ustar garethtanstaff00000000000000[bdist_wheel] universal = 1 [egg_info] tag_build = tag_date = 0 fuzzywuzzy-0.18.0/README.rst0000644000076600000240000001014113621334446016713 0ustar garethtanstaff00000000000000.. image:: https://travis-ci.org/seatgeek/fuzzywuzzy.svg?branch=master :target: https://travis-ci.org/seatgeek/fuzzywuzzy FuzzyWuzzy ========== Fuzzy string matching like a boss. It uses `Levenshtein Distance `_ to calculate the differences between sequences in a simple-to-use package. Requirements ============ - Python 2.7 or higher - difflib - `python-Levenshtein `_ (optional, provides a 4-10x speedup in String Matching, though may result in `differing results for certain cases `_) For testing ~~~~~~~~~~~ - pycodestyle - hypothesis - pytest Installation ============ Using PIP via PyPI .. code:: bash pip install fuzzywuzzy or the following to install `python-Levenshtein` too .. code:: bash pip install fuzzywuzzy[speedup] Using PIP via Github .. code:: bash pip install git+git://github.com/seatgeek/fuzzywuzzy.git@0.18.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.18.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!") 97 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") 91 >>> 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) You can also pass additional parameters to ``extractOne`` method to make it use a specific scorer. A typical use case is to match file paths: .. code:: python >>> process.extractOne("System of a down - Hypnotize - Heroin", songs) ('/music/library/good/System of a Down/2005 - Hypnotize/01 - Attack.mp3', 86) >>> process.extractOne("System of a down - Hypnotize - Heroin", songs, scorer=fuzz.token_sort_ratio) ("/music/library/good/System of a Down/2005 - Hypnotize/10 - She's Like Heroin.mp3", 61) .. |Build Status| image:: https://api.travis-ci.org/seatgeek/fuzzywuzzy.png?branch=master :target: https:travis-ci.org/seatgeek/fuzzywuzzy Known Ports ============ FuzzyWuzzy is being ported to other languages too! Here are a few ports we know about: - Java: `xpresso's fuzzywuzzy implementation `_ - Java: `fuzzywuzzy (java port) `_ - Rust: `fuzzyrusty (Rust port) `_ - JavaScript: `fuzzball.js (JavaScript port) `_ - C++: `Tmplt/fuzzywuzzy `_ - C#: `fuzzysharp (.Net port) `_ - Go: `go-fuzzywuzz (Go port) `_ - Free Pascal: `FuzzyWuzzy.pas (Free Pascal port) `_ - Kotlin multiplatform: `FuzzyWuzzy-Kotlin `_ - R: `fuzzywuzzyR (R port) `_ fuzzywuzzy-0.18.0/LICENSE.txt0000644000076600000240000004324413562561512017061 0ustar garethtanstaff00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19yy name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License.fuzzywuzzy-0.18.0/CHANGES.rst0000644000076600000240000005054613562561512017043 0ustar garethtanstaff00000000000000Changelog ========= 0.17.0 (2018-08-20) ------------------- - Make benchmarks script Py3 compatible. [Stefan Behnel] - Add Go lang port. [iddober] - Add reference to C# port. [ericcoleman] - Chore: remove license header from files. [Jose Diaz-Gonzalez] The files should all inherit the projects license. - Fix README title style. [Thomas Grainger] - Add readme check. [Thomas Grainger] install docutils and Pygments - Cache pip. [Thomas Grainger] - Upgrade pip/setuptools for hypothesis. [Thomas Grainger] - Feat: drop py26 and py33 support from tox. [Jose Diaz-Gonzalez] - Feat: drop support for 2.6 in test_fuzzywuzzy.py. [Jose Diaz-Gonzalez] - Feat: drop reference to 2.4 from readme. [Jose Diaz-Gonzalez] - Feat: drop py2.6 and py3.3 classifiers. [Jose Diaz-Gonzalez] - Feat: drop 2.6 and 3.3 support. [Jose Diaz-Gonzalez] These are no longer supported. Please upgrade your python version if you are using either version. - Fuzz: _token_sort: check for equivalence. [Ralf Ramsauer] If we don't have to full_process the strings, we can safely assume to return 100 in case both candidates equal. Signed-off-by: Ralf Ramsauer - Test: add more test cases. [Ralf Ramsauer] Signed-off-by: Ralf Ramsauer - Utils: add and use check_for_equivalence decorator. [Ralf Ramsauer] And decorate basic scoring functions. The check_for_equivalence decorator MUST be used after the check_for_none decorator, as otherwise ratio(None, None) will get a score of 100. This fixes the first part of the recently introduced changes in the test set. Signed-off-by: Ralf Ramsauer - Tests: add some corner cases. [Ralf Ramsauer] '' and '' are equal, so are '{' and '{'. Test if fuzzywuzzy gives them a score of 100. For the moment, this patch breaks tests, fixes in fuzzywuzzy follow. Signed-off-by: Ralf Ramsauer - Utils: remove superfluous check. [Ralf Ramsauer] Decorators make sure that only non None-values are passed. We can safely assume that None will never get here. Other than that, None's shouldn't simply be ignored and erroneously changed to empty strings. Better let users fail. This commit doesn't break any tests. Signed-off-by: Ralf Ramsauer - README: add missing requirements. [Ralf Ramsauer] pycodestyle and hypothesis are required for automatic testing. Add them to README's requirement section. Signed-off-by: Ralf Ramsauer - Remove empty document. [Ralf Ramsauer] Signed-off-by: Ralf Ramsauer 0.16.0 (2017-12-18) ------------------- - Add punctuation characters back in so process does something. [davidcellis] - Simpler alphabet and even fewer examples. [davidcellis] - Fewer examples and larger deadlines for Hypothesis. [davidcellis] - Slightly more examples. [davidcellis] - Attempt to fix the failing 2.7 and 3.6 python tests. [davidcellis] - Readme: add link to C++ port. [Lizard] - Fix tests on Python 3.3. [Jon Banafato] Modify tox.ini and .travis.yml to install enum34 when running with Python 3.3 to allow hypothesis tests to pass. - Normalize Python versions. [Jon Banafato] - Enable Travis-CI tests for Python 3.6 - Enable tests for all supported Python versions in tox.ini - Add Trove classifiers for Python 3.4 - 3.6 to setup.py --- Note: Python 2.6 and 3.3 are no longer supported by the Python core team. Support for these can likely be dropped, but that's out of scope for this change set. - Fix typos. [Sven-Hendrik Haase] 0.15.1 (2017-07-19) ------------------- - Fix setup.py (addresses #155) [Paul O'Leary McCann] - Merge remote-tracking branch 'upstream/master' into extract_optimizations. [nolan] - Seed random before generating benchmark strings. [nolan] - Cleaner implementation of same idea without new param, but adding existing full_process param to Q,W,UQ,UW. [nolan] - Fix benchmark only generate list once. [nolan] - Only run util.full_process once on query when using extract functions, add new benchmarks. [nolan] 0.15.0 (2017-02-20) ------------------- - Add extras require to install python-levenshtein optionally. [Rolando Espinoza] This allows to install python-levenshtein as dependency. - Fix link formatting in the README. [Alex Chan] - Add fuzzball.js JavaScript port link. [nolan] - Added Rust Port link. [Logan Collins] - Validate_string docstring. [davidcellis] - For full comparisons test that ONLY exact matches (after processing) are added. [davidcellis] - Add detailed docstrings to WRatio and QRatio comparisons. [davidcellis] 0.14.0 (2016-11-04) ------------------- - Possible PEP-8 fix + make pep-8 warnings appear in test. [davidcellis] - Possible PEP-8 fix. [davidcellis] - Possible PEP-8 fix. [davidcellis] - Test for stderr log instead of warning. [davidcellis] - Convert warning.warn to logging.warning. [davidcellis] - Additional details for empty string warning from process. [davidcellis] String formatting fix for python 2.6 - Enclose warnings.simplefilter() inside a with statement. [samkennerly] 0.13.0 (2016-11-01) ------------------- - Support alternate git status output. [Jose Diaz-Gonzalez] - Split warning test into new test file, added to travis execution on 2.6 / pypy3. [davidcellis] - Remove hypothesis examples database from gitignore. [davidcellis] - Add check for warning to tests. [davidcellis] Reordered test imports - Check processor and warn before scorer may remove processor. [davidcellis] - Renamed test - tidied docstring. [davidcellis] - Add token ratios to the list of scorers that skip running full_process as a processor. [davidcellis] - Added tokex_sort, token_set to test. [davidcellis] - Test docstrings/comments. [davidcellis] Removed redundant check from test. - Added py.test .cache/ removed duplicated build from gitignore. [davidcellis] - Added default_scorer, default_processor parameters to make it easier to change in the future. [davidcellis] Added warning if the processor reduces the input query to an empty string. - Rewrote extracts to explicitly use default values for processor and scorer. [davidcellis] - Changed Hypothesis tests to use pytest parameters. [davidcellis] - Added Hypothesis based tests for identical strings. [Ducksual] Added support for hypothesis to travis config. Hypothesis based tests are skipped on Python 2.6 and pypy3. Added .hypothesis/ folder to gitignore - Added test for simple 'a, b' string on process.extractOne. [Ducksual] - Process the query in process.extractWithoutOrder when using a scorer which does not do so. [Ducksual] Closes 139 - Mention that difflib and levenshtein results may differ. [Jose Diaz- Gonzalez] Closes #128 0.12.0 (2016-09-14) ------------------- - Declare support for universal wheels. [Thomas Grainger] - Clarify that license is GPLv2. [Gareth Tan] 0.11.1 (2016-07-27) ------------------- - Add editorconfig. [Jose Diaz-Gonzalez] - Added tox.ini cofig file for easy local multi-environment testing changed travis config to use py.test like tox updated use of pep8 module to pycodestyle. [Pedro Rodrigues] 0.11.0 (2016-06-30) ------------------- - Clean-up. [desmaisons_david] - Improving performance. [desmaisons_david] - Performance Improvement. [desmaisons_david] - Fix link to Levenshtein. [Brian J. McGuirk] - Fix readme links. [Brian J. McGuirk] - Add license to StringMatcher.py. [Jose Diaz-Gonzalez] Closes #113 0.10.0 (2016-03-14) ------------------- - 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.18.0/test_fuzzywuzzy.py0000644000076600000240000004420513562561512021165 0ustar garethtanstaff00000000000000# -*- coding: utf8 -*- from __future__ import unicode_literals import unittest import re import sys import pycodestyle 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 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' # test silly corner cases self.s8 = '{' self.s8a = '{' self.s9 = '{a' self.s9a = '{a' self.s10 = 'a{' self.s10a = '{b' 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) self.assertEqual(fuzz.ratio(self.s8, self.s8a), 100) self.assertEqual(fuzz.ratio(self.s9, self.s9a), 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) self.assertEqual(fuzz.partial_token_sort_ratio(self.s8, self.s8a, full_process=False), 100) self.assertEqual(fuzz.partial_token_sort_ratio(self.s9, self.s9a, full_process=True), 100) self.assertEqual(fuzz.partial_token_sort_ratio(self.s9, self.s9a, full_process=False), 100) self.assertEqual(fuzz.partial_token_sort_ratio(self.s10, self.s10a, full_process=False), 50) def testTokenSetRatio(self): self.assertEqual(fuzz.token_set_ratio(self.s4, self.s5), 100) self.assertEqual(fuzz.token_set_ratio(self.s8, self.s8a, full_process=False), 100) self.assertEqual(fuzz.token_set_ratio(self.s9, self.s9a, full_process=True), 100) self.assertEqual(fuzz.token_set_ratio(self.s9, self.s9a, full_process=False), 100) self.assertEqual(fuzz.token_set_ratio(self.s10, self.s10a, full_process=False), 50) 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 testEmptyStringsScore100(self): self.assertEqual(fuzz.ratio("", ""), 100) self.assertEqual(fuzz.partial_ratio("", ""), 100) 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", "CitiField", "2017-03-19", "8pm"], 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) def test_simplematch(self): basic_string = 'a, b' match_strings = ['a, b'] result = process.extractOne(basic_string, match_strings, scorer=fuzz.ratio) part_result = process.extractOne(basic_string, match_strings, scorer=fuzz.partial_ratio) self.assertEqual(result, ('a, b', 100)) self.assertEqual(part_result, ('a, b', 100)) class TestCodeFormat(unittest.TestCase): def test_pep8_conformance(self): pep8style = pycodestyle.StyleGuide(quiet=False) 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