diff --git a/.github/workflows/greetings.yml b/.github/workflows/greetings.yml deleted file mode 100644 index 3ed2dc4..0000000 --- a/.github/workflows/greetings.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Greetings - -on: [pull_request, issues] - -jobs: - greeting: - runs-on: ubuntu-latest - steps: - - uses: actions/first-interaction@v1 - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - issue-message: 'Thanks for your first issue!' - pr-message: 'Thanks for your first pr!' diff --git a/.github/workflows/python-package.yml b/.github/workflows/python-package.yml index 7033cf8..c05faa7 100644 --- a/.github/workflows/python-package.yml +++ b/.github/workflows/python-package.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python-version: [3.5, 3.6, 3.7, 3.8] + python-version: [3.5, 3.6, 3.7, 3.8, 3.9] steps: - uses: actions/checkout@v2 diff --git a/README.md b/README.md index 2e0b8d4..72c3f6c 100644 --- a/README.md +++ b/README.md @@ -393,9 +393,16 @@ Distance is computed as 1 - similarity. ### SIFT4 SIFT4 is a general purpose string distance algorithm inspired by JaroWinkler and Longest Common Subsequence. It was developed to produce a distance measure that matches as close as possible to the human perception of string distance. Hence it takes into account elements like character substitution, character distance, longest common subsequence etc. It was developed using experimental testing, and without theoretical background. -**Not implemented yet** +```python +from strsimpy import SIFT4 +s = SIFT4() +# result: 11.0 +s.distance('This is the first string', 'And this is another string') # 11.0 +# result: 12.0 +s.distance('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Amet Lorm ispum dolor sit amet, consetetur adixxxpiscing elit.', maxoffset=10) +``` ## Users * [StringSimilarity.NET](https://github.com/feature23/StringSimilarity.NET) a .NET port of java-string-similarity diff --git a/setup.py b/setup.py index 6407c98..20da3f8 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="strsimpy", - version="0.1.7", + version="0.2.1", description="A library implementing different string similarity and distance measures", long_description=long_description, long_description_content_type="text/markdown", @@ -22,6 +22,7 @@ "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ) diff --git a/strsimpy/__init__.py b/strsimpy/__init__.py index a80015b..1b1792f 100644 --- a/strsimpy/__init__.py +++ b/strsimpy/__init__.py @@ -34,6 +34,7 @@ from .string_distance import StringDistance from .string_similarity import StringSimilarity from .weighted_levenshtein import WeightedLevenshtein +from .sift4 import SIFT4Options, SIFT4 __name__ = 'strsimpy' -__version__ = '0.1.7' +__version__ = '0.2.1' diff --git a/strsimpy/ngram.py b/strsimpy/ngram.py index c3860b7..27d4ae1 100644 --- a/strsimpy/ngram.py +++ b/strsimpy/ngram.py @@ -46,7 +46,7 @@ def distance(self, s0, s1): for i in range(min(sl, tl)): if s0[i] == s1[i]: cost += 1 - return 1.0 * cost / max(sl, tl) + return 1.0 - cost / max(sl, tl) sa = [''] * (sl + self.n - 1) diff --git a/strsimpy/sift4.py b/strsimpy/sift4.py new file mode 100644 index 0000000..76adc52 --- /dev/null +++ b/strsimpy/sift4.py @@ -0,0 +1,188 @@ +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. +from .string_distance import MetricStringDistance + + +class SIFT4Options(MetricStringDistance): + def __init__(self, options=None): + self.options = { + 'maxdistance': 0, + 'tokenizer': lambda x: [i for i in x], + 'tokenmatcher': lambda t1, t2: t1 == t2, + 'matchingevaluator': lambda t1, t2: 1, + 'locallengthevaluator': lambda x: x, + 'transpositioncostevaluator': lambda c1, c2: 1, + 'transpositionsevaluator': lambda lcss, trans: lcss - trans + } + otheroptions = { + 'tokenizer': { + 'ngram': self.ngramtokenizer, + 'wordsplit': self.wordsplittokenizer, + 'characterfrequency': self.characterfrequencytokenizer + }, + 'tokematcher': {'sift4tokenmatcher': self.sift4tokenmatcher}, + 'matchingevaluator': {'sift4matchingevaluator': self.sift4matchingevaluator}, + 'locallengthevaluator': { + 'rewardlengthevaluator': self.rewardlengthevaluator, + 'rewardlengthevaluator2': self.rewardlengthevaluator2 + }, + 'transpositioncostevaluator': {'longertranspositionsaremorecostly':self.longertranspositionsaremorecostly}, + 'transpositionsevaluator': {} + } + if isinstance(options, dict): + for k, v in options.items(): + if k in self.options.keys(): + if k == 'maxdistance': + if isinstance(v, int): + self.options[k] = v + else: + raise ValueError("Option maxdistance should be int") + else: + if callable(v): + self.options[k] = v + else: + if v in otheroptions[k].keys(): + self.options[k] = otheroptions[k][v] + else: + msg = "Option {} should be callable or one of [{}]".format(k, ', '.join(otheroptions[k].keys())) + raise ValueError(msg) + else: + raise ValueError("Option {} not recognized.".format(k)) + elif options is not None: + raise ValueError("options should be a dictionary") + self.maxdistance = self.options['maxdistance'] + self.tokenizer = self.options['tokenizer'] + self.tokenmatcher = self.options['tokenmatcher'] + self.matchingevaluator = self.options['matchingevaluator'] + self.locallengthevaluator = self.options['locallengthevaluator'] + self.transpositioncostevaluator = self.options['transpositioncostevaluator'] + self.transpositionsevaluator = self.options['transpositionsevaluator'] + + # tokenizers: + @staticmethod + def ngramtokenizer(s, n): + result = [] + if not s: + return result + for i in range(len(s) - n - 1): + result.append(s[i:(i + n)]) + return result + + @staticmethod + def wordsplittokenizer(s): + if not s: + return [] + return s.split() + + @staticmethod + def characterfrequencytokenizer(s): + letters = [i for i in 'abcdefghijklmnopqrstuvwxyz'] + return [s.lower().count(x) for x in letters] + + # tokenMatchers: + @staticmethod + def sift4tokenmatcher(t1, t2): + similarity = 1 - SIFT4().distance(t1, t2, 5) / max(len(t1), len(t2)) + return similarity > 0.7 + + # matchingEvaluators: + @staticmethod + def sift4matchingevaluator(t1, t2): + similarity = 1 - SIFT4().distance(t1, t2, 5) / max(len(t1), len(t2)) + return similarity + + # localLengthEvaluators: + @staticmethod + def rewardlengthevaluator(l): + if l < 1: + return l + return l - 1 / (l + 1) + + @staticmethod + def rewardlengthevaluator2(l): + return pow(l, 1.5) + + # transpositionCostEvaluators: + @staticmethod + def longertranspositionsaremorecostly(c1, c2): + return abs(c2 - c1) / 9 + 1 + + +class SIFT4: + # As described in https://siderite.dev/blog/super-fast-and-accurate-string-distance.html/ + def distance(self, s1, s2, maxoffset=5, options=None): + options = SIFT4Options(options) + t1, t2 = options.tokenizer(s1), options.tokenizer(s2) + l1, l2 = len(t1), len(t2) + if l1 == 0: + return l2 + if l2 == 0: + return l1 + + c1, c2, lcss, local_cs, trans, offset_arr = 0, 0, 0, 0, 0, [] + while (c1 < l1) and (c2 < l2): + if options.tokenmatcher(t1[c1], t2[c2]): + local_cs += options.matchingevaluator(t1[c1], t2[c2]) + isTrans = False + i = 0 + while i < len(offset_arr): + ofs = offset_arr[i] + if (c1 <= ofs['c1']) or (c2 <= ofs['c2']): + isTrans = abs(c2 - c1) >= abs(ofs['c2'] - ofs['c1']) + if isTrans: + trans += options.transpositioncostevaluator(c1, c2) + else: + if not ofs['trans']: + ofs['trans'] = True + trans += options.transpositioncostevaluator(ofs['c1'], ofs['c2']) + break + else: + if (c1 > ofs['c2']) and (c2 > ofs['c1']): + offset_arr.pop(i) + else: + i += 1 + offset_arr.append({'c1': c1, 'c2': c2, 'trans': isTrans}) + else: + lcss += options.locallengthevaluator(local_cs) + local_cs = 0 + if c1 != c2: + c1 = c2 = min(c1, c2) + for i in range(maxoffset): + if (c1 + i < l1) or (c2 + i < l2): + if (c1 + i < l1) and options.tokenmatcher(t1[c1 + i], t2[c2]): + c1 += i - 1 + c2 -= 1 + break + if (c2 + i < l2) and options.tokenmatcher(t1[c1], t2[c2 + i]): + c1 -= 1 + c2 += i - 1 + break + c1 += 1 + c2 += 1 + if options.maxdistance: + temporarydistance = options.locallengthevaluator(max(c1, c2)) - options.transpositionsevaluator(lcss, trans) + if temporarydistance >= options.maxdistance: + return round(temporarydistance) + if (c1 >= l1) or (c2 >= l2): + lcss += options.locallengthevaluator(local_cs) + local_cs = 0 + c1 = c2 = min(c1, c2) + lcss += options.locallengthevaluator(local_cs) + return round(options.locallengthevaluator(max(l1, l2)) - options.transpositionsevaluator(lcss, trans)) + + diff --git a/strsimpy/sift4_test.py b/strsimpy/sift4_test.py new file mode 100644 index 0000000..1960e7b --- /dev/null +++ b/strsimpy/sift4_test.py @@ -0,0 +1,21 @@ +import unittest + +from .sift4 import SIFT4 + + +class SIFT4Test(unittest.TestCase): + + def testSIFT4(self): + s = SIFT4() + + results = [ + ('This is the first string', 'And this is another string', 5, 11.0), + ('Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Amet Lorm ispum dolor sit amet, consetetur adixxxpiscing elit.', 10, 12.0) + ] + + for a, b, offset, res in results: + self.assertEqual(res, s.distance(a, b, maxoffset=offset)) + + +if __name__ == "__main__": + unittest.main() diff --git a/strsimpy/weighted_levenshtein.py b/strsimpy/weighted_levenshtein.py index c225e1a..a03b460 100644 --- a/strsimpy/weighted_levenshtein.py +++ b/strsimpy/weighted_levenshtein.py @@ -18,6 +18,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. +from functools import reduce from .string_distance import StringDistance @@ -52,9 +53,9 @@ def distance(self, s0, s1): if s0 == s1: return 0.0 if len(s0) == 0: - return len(s1) + return reduce(lambda cost, char: cost + self.insertion_cost_fn(char), s1, 0) if len(s1) == 0: - return len(s0) + return reduce(lambda cost, char: cost + self.deletion_cost_fn(char), s0, 0) v0, v1 = [0.0] * (len(s1) + 1), [0.0] * (len(s1) + 1) @@ -63,16 +64,16 @@ def distance(self, s0, s1): v0[i] = v0[i - 1] + self.insertion_cost_fn(s1[i - 1]) for i in range(len(s0)): - s1i = s0[i] - deletion_cost = self.deletion_cost_fn(s1i) + s0i = s0[i] + deletion_cost = self.deletion_cost_fn(s0i) v1[0] = v0[0] + deletion_cost for j in range(len(s1)): - s2j = s1[j] + s1j = s1[j] cost = 0 - if s1i != s2j: - cost = self.substitution_cost_fn(s1i, s2j) - insertion_cost = self.insertion_cost_fn(s2j) + if s0i != s1j: + cost = self.substitution_cost_fn(s0i, s1j) + insertion_cost = self.insertion_cost_fn(s1j) v1[j + 1] = min(v1[j] + insertion_cost, v0[j + 1] + deletion_cost, v0[j] + cost) v0, v1 = v1, v0