From 5c11630384f4671645e5235a3446460227c6249b Mon Sep 17 00:00:00 2001 From: Motti Lanzkron Date: Tue, 8 Sep 2020 08:52:42 +0300 Subject: [PATCH 01/12] Make names of variables reflect what they mean Rename the variable for `s0[i]` from `s1i` to `s0i` and similarly for `s1[j]` --- strsimpy/weighted_levenshtein.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/strsimpy/weighted_levenshtein.py b/strsimpy/weighted_levenshtein.py index c225e1a..7565b27 100644 --- a/strsimpy/weighted_levenshtein.py +++ b/strsimpy/weighted_levenshtein.py @@ -63,16 +63,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 From 106489c6b585f9b8a839628c115286179c7dd4ec Mon Sep 17 00:00:00 2001 From: Motti Lanzkron Date: Wed, 9 Sep 2020 15:32:37 +0300 Subject: [PATCH 02/12] use specified costs when one of the strings is empty If one of the strings is empty it's not correct to assume that the cost is the length of the other string since we the insertion and deletion costs are configurable and not necessarily 1. --- strsimpy/weighted_levenshtein.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/strsimpy/weighted_levenshtein.py b/strsimpy/weighted_levenshtein.py index 7565b27..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) From 9c85f50aae4986ad24ab3ffd20f9969f126110e0 Mon Sep 17 00:00:00 2001 From: luozhouyang Date: Tue, 22 Sep 2020 15:30:25 +0800 Subject: [PATCH 03/12] Bump version to 0.1.8 --- setup.py | 2 +- strsimpy/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 6407c98..609c9b6 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="strsimpy", - version="0.1.7", + version="0.1.8", description="A library implementing different string similarity and distance measures", long_description=long_description, long_description_content_type="text/markdown", diff --git a/strsimpy/__init__.py b/strsimpy/__init__.py index a80015b..4e9778c 100644 --- a/strsimpy/__init__.py +++ b/strsimpy/__init__.py @@ -36,4 +36,4 @@ from .weighted_levenshtein import WeightedLevenshtein __name__ = 'strsimpy' -__version__ = '0.1.7' +__version__ = '0.1.8' From 10a589df1cd0a75345013b9cf6d62ac2e2ddc74e Mon Sep 17 00:00:00 2001 From: Matthijs Date: Thu, 24 Sep 2020 15:15:28 +0200 Subject: [PATCH 04/12] Added SIFT4 --- README.md | 2 - setup.py | 2 +- strsimpy/__init__.py | 3 +- strsimpy/sift4.py | 188 +++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 191 insertions(+), 4 deletions(-) create mode 100644 strsimpy/sift4.py diff --git a/README.md b/README.md index 2e0b8d4..b1067ea 100644 --- a/README.md +++ b/README.md @@ -393,8 +393,6 @@ 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** - ## Users diff --git a/setup.py b/setup.py index 609c9b6..99f057c 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="strsimpy", - version="0.1.8", + version="0.1.9", description="A library implementing different string similarity and distance measures", long_description=long_description, long_description_content_type="text/markdown", diff --git a/strsimpy/__init__.py b/strsimpy/__init__.py index 4e9778c..37a5e4f 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 SIFT4 __name__ = 'strsimpy' -__version__ = '0.1.8' +__version__ = '0.1.9' 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)) + + From 9d20a36f610e88d6561dc4a887f41cb434e3963f Mon Sep 17 00:00:00 2001 From: luozhouyang Date: Fri, 25 Sep 2020 09:41:14 +0800 Subject: [PATCH 05/12] Remove greetings --- .github/workflows/greetings.yml | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 .github/workflows/greetings.yml 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!' From 1d7e32198e44210aac13c72d1b83b22e57b26513 Mon Sep 17 00:00:00 2001 From: luozhouyang Date: Fri, 25 Sep 2020 10:07:40 +0800 Subject: [PATCH 06/12] Perfect SIFT4 --- README.md | 9 +++++++++ strsimpy/__init__.py | 2 +- strsimpy/sift4_test.py | 21 +++++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 strsimpy/sift4_test.py diff --git a/README.md b/README.md index b1067ea..72c3f6c 100644 --- a/README.md +++ b/README.md @@ -393,7 +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. +```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/strsimpy/__init__.py b/strsimpy/__init__.py index 37a5e4f..1e10460 100644 --- a/strsimpy/__init__.py +++ b/strsimpy/__init__.py @@ -34,7 +34,7 @@ from .string_distance import StringDistance from .string_similarity import StringSimilarity from .weighted_levenshtein import WeightedLevenshtein -from .sift4 import SIFT4 +from .sift4 import SIFT4Options, SIFT4 __name__ = 'strsimpy' __version__ = '0.1.9' diff --git a/strsimpy/sift4_test.py b/strsimpy/sift4_test.py new file mode 100644 index 0000000..039d8b5 --- /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.assertEquals(res, s.distance(a, b, maxoffset=offset)) + + +if __name__ == "__main__": + unittest.main() From 932952dbca07e57aa50ddc77cfd8507d62b34089 Mon Sep 17 00:00:00 2001 From: Martin Pajuste Date: Tue, 1 Dec 2020 16:16:57 +0200 Subject: [PATCH 07/12] Test Python 3.9 --- .github/workflows/python-package.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 2c2d5786c25b0b626f08d6a13821290bae45de3f Mon Sep 17 00:00:00 2001 From: Martin Pajuste Date: Tue, 1 Dec 2020 16:31:07 +0200 Subject: [PATCH 08/12] Update setup.py --- setup.py | 1 + 1 file changed, 1 insertion(+) diff --git a/setup.py b/setup.py index 99f057c..3526c39 100644 --- a/setup.py +++ b/setup.py @@ -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", ) From 2efcfe7a8f095964609eba6c985d70426d2a1bc1 Mon Sep 17 00:00:00 2001 From: luozhouyang Date: Tue, 15 Dec 2020 10:40:51 +0800 Subject: [PATCH 09/12] Release v0.2.0 --- setup.py | 2 +- strsimpy/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 3526c39..5b18632 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="strsimpy", - version="0.1.9", + version="0.2.0", description="A library implementing different string similarity and distance measures", long_description=long_description, long_description_content_type="text/markdown", diff --git a/strsimpy/__init__.py b/strsimpy/__init__.py index 1e10460..f897911 100644 --- a/strsimpy/__init__.py +++ b/strsimpy/__init__.py @@ -37,4 +37,4 @@ from .sift4 import SIFT4Options, SIFT4 __name__ = 'strsimpy' -__version__ = '0.1.9' +__version__ = '0.2.0' From 060e1372c2b029eb637c5c205f336b5f89374c7a Mon Sep 17 00:00:00 2001 From: Adam Horacek Date: Fri, 10 Sep 2021 08:33:41 +0200 Subject: [PATCH 10/12] fix ngram distance for strings shorter then N --- strsimpy/ngram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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) From 060a51ca863ff335775ac29cb2ded186fd88062a Mon Sep 17 00:00:00 2001 From: luozhouyang Date: Fri, 10 Sep 2021 17:11:35 +0800 Subject: [PATCH 11/12] Release v0.2.1 --- setup.py | 2 +- strsimpy/__init__.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/setup.py b/setup.py index 5b18632..20da3f8 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setuptools.setup( name="strsimpy", - version="0.2.0", + version="0.2.1", description="A library implementing different string similarity and distance measures", long_description=long_description, long_description_content_type="text/markdown", diff --git a/strsimpy/__init__.py b/strsimpy/__init__.py index f897911..1b1792f 100644 --- a/strsimpy/__init__.py +++ b/strsimpy/__init__.py @@ -37,4 +37,4 @@ from .sift4 import SIFT4Options, SIFT4 __name__ = 'strsimpy' -__version__ = '0.2.0' +__version__ = '0.2.1' From fca3b16a3e149c28cb5936eeb2a1f1e0f8f967b7 Mon Sep 17 00:00:00 2001 From: Karthikeyan Singaravelan Date: Mon, 11 Oct 2021 11:35:49 +0000 Subject: [PATCH 12/12] Refactor deprecated unittest aliases for Python 3.11 compatibility. --- strsimpy/sift4_test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/strsimpy/sift4_test.py b/strsimpy/sift4_test.py index 039d8b5..1960e7b 100644 --- a/strsimpy/sift4_test.py +++ b/strsimpy/sift4_test.py @@ -14,7 +14,7 @@ def testSIFT4(self): ] for a, b, offset, res in results: - self.assertEquals(res, s.distance(a, b, maxoffset=offset)) + self.assertEqual(res, s.distance(a, b, maxoffset=offset)) if __name__ == "__main__":