Created
September 28, 2018 05:16
-
-
Save kzinmr/d308aeb96391f4bb40d0fc84cb536a7d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# char-ngram jaccard sim | |
from nltk import ngrams | |
from nltk.metrics import jaccard_distance | |
def ngram(sequence_list, n=3): | |
return [''.join(grams) for i in range(1, n) for grams in ngrams(sequence_list, i)] | |
def jaccard_similarity(s1, s2): | |
if len(set(s1)) and len(set(s2)): | |
return 1. - jaccard_distance(set(s1), set(s2)) | |
else: | |
return 0. | |
def char_overlap(s1, s2, n=3): | |
cngram1 = ngram(''.join(s1.split(' ')), n=n) | |
cngram2 = ngram(''.join(s2.split(' ')), n=n) | |
return jaccard_similarity(cngram1, cngram2) | |
def word_overlap(s1, s2): | |
wngram1 = ngram(s1.split(' '), n=1) | |
wngram2 = ngram(s2.split(' '), n=1) | |
return jaccard_similarity(wngram1, wngram2) | |
def sort_by_overlap(q, slist): | |
olist = [char_overlap(q, s) for s in slist] | |
solist = sorted(zip(slist, olist), key=lambda x:-x[-1]) | |
return solist |
Author
kzinmr
commented
Jan 6, 2023
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment