-
Notifications
You must be signed in to change notification settings - Fork 0
/
stringcmp.py
2698 lines (2139 loc) · 93.5 KB
/
stringcmp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# =============================================================================
# AUSTRALIAN NATIONAL UNIVERSITY OPEN SOURCE LICENSE (ANUOS LICENSE)
# VERSION 1.3
#
# The contents of this file are subject to the ANUOS License Version 1.3
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at:
#
# https://sourceforge.net/projects/febrl/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
# the License for the specific language governing rights and limitations
# under the License.
#
# The Original Software is: "stringcmp.py"
#
# The Initial Developer of the Original Software is:
# Dr Peter Christen (Research School of Computer Science, The Australian
# National University)
#
# Copyright (C) 2002 - 2011 the Australian National University and
# others. All Rights Reserved.
#
# Contributors:
#
# Alternatively, the contents of this file may be used under the terms
# of the GNU General Public License Version 2 or later (the "GPL"), in
# which case the provisions of the GPL are applicable instead of those
# above. The GPL is available at the following URL: http://www.gnu.org/
# If you wish to allow use of your version of this file only under the
# terms of the GPL, and not to allow others to use your version of this
# file under the terms of the ANUOS License, indicate your decision by
# deleting the provisions above and replace them with the notice and
# other provisions required by the GPL. If you do not delete the
# provisions above, a recipient may use your version of this file under
# the terms of any one of the ANUOS License or the GPL.
# =============================================================================
#
# Freely extensible biomedical record linkage (Febrl) - Version 0.4.2
#
# See: http://datamining.anu.edu.au/linkage.html
#
# =============================================================================
"""Module with various approximate string comparison methods.
Provides routines for various approximate string comparisons. All return a
similarity value between 0.0 (strings are totally different) to 1.0 (strings
are the same).
Comparison methods provided:
exact Exact comparison
jaro Jaro
winkler Winkler (based on Jaro) (for backwards compatibility)
qgram q-gram based
bigram 2-gram based (for backwards compatibility)
posqgram Positional q-gram based
sgram Skip-gram based
editdist Edit-distance (or Levenshtein distance)
mod_editdist Modified edit-distance (with transposition cost 1, not 2)
bagdist Bag distance (cheap distance based method)
swdist Smith-Waternam distance
syllaligndist Syllable alignment distance
seqmatch Uses Python's standard library 'difflib'
compression Based on Zlib compression algorithm
lcs (Repeated) longest common substring, improves results for
swapped words
ontolcs Ontology alignment string comparison based on longest common
substring, Hamacher product and Winkler heuristics.
permwinkler Winkler combined with permutations of words, improves results
for swapped words
sortwinkler Winkler with sorted words (if more than one), improves results
for swapped words
editex Phonetic aware edit-distance (Zobel et al. 1996)
twoleveljaro Apply Jaro comparator at word level, with words being compared
using a selectable approximate string comparison function
charhistogram Get histogram of characters for both strings and calculate the
cosine similarity between the two histogram vectors
See doc strings of individual functions for detailed documentation.
If called from command line, a test routine is run which prints example
approximate string comparisons for various string pairs.
"""
# =============================================================================
# Imports go here
import bz2
import difflib
import logging
import math
import time
import zlib
import encode # For Phonix transformation routine (used in syllable alignment
# distance)
import mymath # Contains arithmetic coder
# =============================================================================
# Special character used in the Jaro, Winkler and q-gram comparions functions.
# Thanks to Luca Montecchiani (luca.mon@aliceposta.it).
#
JARO_MARKER_CHAR = chr(1)
QGRAM_START_CHAR = chr(1)
QGRAM_END_CHAR = chr(2)
# =============================================================================
def do_stringcmp(cmp_method, str1, str2, min_threshold = None):
"""A 'chooser' functions which performs the selected comparison method.
For each approximate string comparison method, various callable versions are
provided that set their parameters to commonly used values.
For each method, appending the string '-winkler' will result in the Winkler
modification being applied (increasing the similarity weight if the beginning
of the two strings are the same, up to first four characters).
Possible values for 'cmp_method' are:
exact Exact comparison
jaro Jaro's method
winkler Jaro's method with Winkler modification (same as calling
'jaro-winkler')
qgram1short q-grams of length 1, divisor is shortest string length
qgram1avrg q-grams of length 1, divisor is average string length
qgram1long q-grams of length 1, divisor is longest string length
qgram2short q-grams of length 2, divisor is shortest string length
qgram2avrg q-grams of length 2, divisor is average string length
qgram2long q-grams of length 2, divisor is longest string length
qgram3short q-grams of length 3, divisor is shortest string length
qgram3avrg q-grams of length 3, divisor is average string length
qgram3long q-grams of length 3, divisor is longest string length
qgram1Pshort Padded q-grams of length 1, divisor is shortest string
length
qgram1Pavrg Padded q-grams of length 1, divisor is average string
length
qgram1Plong Padded q-grams of length 1, divisor is longest string
length
qgram2Pshort Padded q-grams of length 2, divisor is shortest string
length
qgram2Pavrg Padded q-grams of length 2, divisor is average string
length
qgram2Plong Padded q-grams of length 2, divisor is longest string
length
qgram3Pshort Padded q-grams of length 3, divisor is shortest string
length
qgram3Pavrg Padded q-grams of length 3, divisor is average string
length
qgram3Plong Padded q-grams of length 3, divisor is longest string
length
posqgram1short Positional q-grams of length 1, divisor is shortest length
posqgram1avrg Positional q-grams of length 1, divisor is average length
posqgram1long Positional q-grams of length 1, divisor is longest string
posqgram2short Positional q-grams of length 2, divisor is shortest length
posqgram2avrg Positional q-grams of length 2, divisor is average length
posqgram2long Positional q-grams of length 2, divisor is longest string
posqgram3short Positional q-grams of length 3, divisor is shortest length
posqgram3avrg Positional q-grams of length 3, divisor is average length
posqgram3long Positional q-grams of length 3, divisor is longest string
posqgram1Pshort Padded positional q-grams of length 1, divisor is shortest
string length
posqgram1Pavrg Padded positional q-grams of length 1, divisor is average
string length
posqgram1Plong Padded positional q-grams of length 1, divisor is longest
string length
posqgram2Pshort Padded positional q-grams of length 2, divisor is shortest
string length
posqgram2Pavrg Padded positional q-grams of length 2, divisor is average
string length
posqgram2Plong Padded positional q-grams of length 2, divisor is longest
string length
posqgram3Pshort Padded positional q-grams of length 3, divisor is shortest
string length
posqgram3Pavrg Padded positional q-grams of length 3, divisor is average
string length
posqgram3lPong Padded positional q-grams of length 3, divisor is longest
string length
sgramshort Skip-grams, divisor is shortest string length
sgramavrg Skip-grams, divisor is average string length
sgramlong Skip-grams, divisor is longest string length
sgramPshort Padded skip-grams, divisor is shortest string length
sgramPavrg Padded skip-grams, divisor is average string length
sgramPlong Padded skip-grams, divisor is longest string length
editdist Edit-distance (or Levenshtein distance)
mod_editdist Modified edit-distance (with transposition cost 1, not 2)
editex Phonetic aware edit-distance (Zobel et al. 1996)
bagdist Bag distance (cheap distance based method)
swdistshort Smith-Waterman distance, divisor is shortest length
swdistavrg Smith-Waterman distance, divisor is average length
swdistlong Smith-Waterman distance, divisor is longest length
syllaldistshort Syllable alignment distance, divisor is shortest length
syllaldistavrg Syllable alignment distance, divisor is average length
syllaldistlong Syllable alignment distance, divisor is longest length
seqmatch Uses Python's standard library 'difflib'
compressZLib Based on Zlib compression algorithm
compressBZ2 Based on BZ2 compression algorithm
compressArith Based on arithmetic compression algorithm
lcs2short Longest common substring with minimum length of substrings
2, and divisor is shortest string length
lcs2avrg Longest common substring with minimum length of substrings
2, and divisor is average string length
lcs2long Longest common substring with minimum length of substrings
2, and divisor is longest string length
lcs3short Longest common substring with minimum length of substrings
3, and divisor is shortest string length
lcs3avrg Longest common substring with minimum length of substrings
3, and divisor is average string length
lcs3long Longest common substring with minimum length of substrings
3, and divisor is longest string length
ontolcs2short Ontology longest common substring with minimum length of
substrings 2, and divisor is shortest string length
ontolcs2avrg Ontology longest common substring with minimum length of
substrings 2, and divisor is average string length
ontolcs2long Ontology longest common substring with minimum length of
substrings 2, and divisor is longest string length
ontolcs3short Ontology longest common substring with minimum length of
substrings 3, and divisor is shortest string length
ontolcs3avrg Ontology longest common substring with minimum length of
substrings 3, and divisor is average string length
ontolcs3long Ontology longest common substring with minimum length of
substrings 3, and divisor is longest string length
permwinkler Winkler combined with permutations of words, improves
results for swapped words
sortwinkler Winkler with sorted words (if more than one), improves
results for swapped words
This functions returns the similarity value (between 0.0 and 1.0) as well as
the time needed to compare the strings (as floating-point value in seconds).
"""
# Check if there is a 'divisor' value given (needed for several methods)
#
if ('short' in cmp_method):
divisor = 'shortest'
elif ('long' in cmp_method):
divisor = 'longest'
elif ('avrg' in cmp_method):
divisor = 'average'
else:
divisor = None
# For q- and s-gram based methods check for a padding 'P'
#
if (('gram' in cmp_method) and ('P' in cmp_method)):
padded = True
else:
padded = False
if (cmp_method.startswith('exa')):
start_time = time.time()
sim_weight = exact(str1, str2)
time_used = time.time() - start_time
elif (cmp_method.startswith('jaro')):
start_time = time.time()
sim_weight = jaro(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('winkler')):
start_time = time.time()
sim_weight = winkler(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('qgram')):
q = int(cmp_method[5]) # Length of q-grams
start_time = time.time()
sim_weight = qgram(str1, str2, q, divisor, min_threshold, padded)
time_used = time.time() - start_time
elif (cmp_method.startswith('posqgram')):
q = int(cmp_method[8]) # Length of q-grams
max_dist = 2
start_time = time.time()
sim_weight = posqgram(str1, str2, q, max_dist, divisor, min_threshold,
padded)
time_used = time.time() - start_time
elif (cmp_method.startswith('sgram')):
start_time = time.time()
sim_weight = sgram(str1, str2, [[0],[0,1],[1,2]], divisor, min_threshold,
padded)
time_used = time.time() - start_time
elif (cmp_method.startswith('editdist')):
start_time = time.time()
sim_weight = editdist(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('mod_editdist')):
start_time = time.time()
sim_weight = mod_editdist(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('swdist')):
start_time = time.time()
sim_weight = swdist(str1, str2, divisor, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('syllaldist')):
start_time = time.time()
sim_weight = syllaligndist(str1, str2, divisor, min_threshold, \
do_phonix=False)
time_used = time.time() - start_time
elif (cmp_method.startswith('bagdist')):
start_time = time.time()
sim_weight = bagdist(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('seqmatch')):
start_time = time.time()
sim_weight = seqmatch(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('compress')):
if ('ZLib' in cmp_method):
compr_method = 'zlib'
elif ('BZ2' in cmp_method):
compr_method = 'bz2'
elif ('Arith' in cmp_method):
compr_method = 'arith'
else:
logging.exception('Illegal compression method given: %s' % (cmp_method))
raise Exception
start_time = time.time()
sim_weight = compression(str1, str2, compr_method, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('lcs')):
m = int(cmp_method[3])
start_time = time.time()
sim_weight = lcs(str1, str2, m, divisor, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('ontolcs')):
m = int(cmp_method[7])
start_time = time.time()
sim_weight = ontolcs(str1, str2, m, divisor, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('sortwinkler')):
start_time = time.time()
sim_weight = sortwinkler(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('permwinkler')):
start_time = time.time()
sim_weight = permwinkler(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (cmp_method.startswith('editex')):
start_time = time.time()
sim_weight = editex(str1, str2, min_threshold)
time_used = time.time() - start_time
elif (not cmp_method.endswith('-winkler')):
logging.exception('Illegal approximate string comparison method: %s' \
% (cmp_method))
raise Exception
# Check if Winkler modification should be applied - - - - - - - - - - - - - -
#
if (cmp_method.endswith('-winkler') == True) and \
(sim_weight > 0.0) and (sim_weight < 1.0):
sim_weight = winklermod(str1, str2, sim_weight)
return sim_weight, time_used
# =============================================================================
def exact(str1, str2):
"""Do exact comparison of two strings.
"""
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
else:
return 0.0
# =============================================================================
def jaro(str1, str2, min_threshold = None):
"""Return approximate string comparator measure (between 0.0 and 1.0)
USAGE:
score = jaro(str1, str2, min_threshold)
ARGUMENTS:
str1 The first string
str2 The second string
min_threshold Minimum threshold between 0 and 1 (currently not used)
DESCRIPTION:
As desribed in 'An Application of the Fellegi-Sunter Model of
Record Linkage to the 1990 U.S. Decennial Census' by William E. Winkler
and Yves Thibaudeau.
"""
# Quick check if the strings are empty or the same - - - - - - - - - - - - -
#
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
len1 = len(str1)
len2 = len(str2)
halflen = max(len1,len2) / 2 - 1 # Or + 1?? PC 12/03/2009
ass1 = '' # Characters assigned in str1
ass2 = '' # Characters assigned in str2
workstr1 = str1 # Copy of original string
workstr2 = str2
common1 = 0 # Number of common characters
common2 = 0
# Analyse the first string - - - - - - - - - - - - - - - - - - - - - - - - -
#
for i in range(len1):
start = max(0,i-halflen)
end = min(i+halflen+1,len2)
index = workstr2.find(str1[i],start,end)
if (index > -1): # Found common character
common1 += 1
ass1 = ass1 + str1[i]
workstr2 = workstr2[:index]+JARO_MARKER_CHAR+workstr2[index+1:]
# Analyse the second string - - - - - - - - - - - - - - - - - - - - - - - - -
#
for i in range(len2):
start = max(0,i-halflen)
end = min(i+halflen+1,len1)
index = workstr1.find(str2[i],start,end)
if (index > -1): # Found common character
common2 += 1
ass2 = ass2 + str2[i]
workstr1 = workstr1[:index]+JARO_MARKER_CHAR+workstr1[index+1:]
if (common1 != common2):
logging.error('Jaro: Wrong common values for strings "%s" and "%s"' % \
(str1, str2) + ', common1: %i, common2: %i' % (common1, common2) + \
', common should be the same.')
common1 = float(common1+common2) / 2.0 ##### This is just a fix #####
if (common1 == 0):
return 0.0
# Compute number of transpositions - - - - - - - - - - - - - - - - - - - - -
#
transposition = 0
for i in range(len(ass1)):
if (ass1[i] != ass2[i]):
transposition += 1
transposition = transposition / 2.0
common1 = float(common1)
w = 1./3.*(common1 / float(len1) + common1 / float(len2) + \
(common1-transposition) / common1)
assert (w >= 0.0) and (w <= 1.0), 'Similarity weight outside 0-1: %f' % (w)
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Jaro comparator string "%s" with "%s" value: %.3f' % \
(str1, str2, w))
return w
# =============================================================================
def winklermod(str1, str2, in_weight):
"""Applies the Winkler modification if beginning of strings is the same.
USAGE:
score = winklermod(str1, str2, in_weight)
ARGUMENTS:
str1 The first string
str2 The second string
in_weight The basic similariy weight calculated by a string comparison
method
DESCRIPTION:
As desribed in 'An Application of the Fellegi-Sunter Model of
Record Linkage to the 1990 U.S. Decennial Census' by William E. Winkler
and Yves Thibaudeau.
If the begining of the two strings (up to fisrt four characters) are the
same, the similarity weight will be increased.
"""
# Quick check if the strings are empty or the same - - - - - - - - - - - - -
#
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
# Compute how many characters are common at beginning - - - - - - - - - - - -
#
minlen = min(len(str1), len(str2))
for same in range(1,minlen+1):
if (str1[:same] != str2[:same]):
break
same -= 1
if (same > 4):
same = 4
assert (same >= 0)
winkler_weight = in_weight + same*0.1 * (1.0 - in_weight)
assert (winkler_weight >= in_weight), 'Winkler modification is negative'
assert (winkler_weight >= 0.0) and (winkler_weight <= 1.0), \
'Similarity weight outside 0-1: %f' % winkler_weight
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Winkler modification for string "%s" and "%s": Input ' % \
(str1, str2)+'weight %.3f modified to %.3f' % \
(in_weight, winkler_weight))
return winkler_weight
# =============================================================================
def winkler(str1, str2, min_threshold = None):
"""For backwards compatibility, call Jaro followed by Winkler modification.
"""
jaro_weight = jaro(str1, str2, min_threshold)
return winklermod(str1, str2, jaro_weight)
# =============================================================================
def qgram(str1, str2, q=2, common_divisor = 'average', min_threshold = None,
padded=True):
"""Return approximate string comparator measure (between 0.0 and 1.0)
using q-grams (with default bigrams: q = 2).
USAGE:
score = qgram(str1, str2, q, common_divisor, min_threshold, padded)
ARGUMENTS:
str1 The first string
str2 The second string
q The length of the q-grams to be used. Must be at least 1.
common_divisor Method of how to calculate the divisor, it can be set to
'average','shortest', or 'longest' , and is calculated
according to the lengths of the two input strings
min_threshold Minimum threshold between 0 and 1
padded If set to True (default), the beginnng and end of the
strings will be padded with (q-1) special characters, if
False no padding will be done.
DESCRIPTION:
q-grams are q-character sub-strings contained in a string. For example,
'peter' contains the bigrams (q=2): ['pe','et','te','er'].
Padding will result in specific q-grams at the beginning and end of a
string, for example 'peter' converted into padded bigrams (q=2) will result
in the following 2-gram list: ['*p','pe','et','te','er','r@'], with '*'
illustrating the start and '@' the end character.
This routine counts the number of common q-grams and divides by the
average number of q-grams. The resulting number is returned.
"""
if (q < 1):
logging.exception('Illegal value for q: %d (must be at least 1)' % (q))
raise Exception
# Quick check if the strings are empty or the same - - - - - - - - - - - - -
#
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
# Calculate number of q-grams in strings (plus start and end characters) - -
#
if (padded == True):
num_qgram1 = len(str1)+q-1
num_qgram2 = len(str2)+q-1
else:
num_qgram1 = max(len(str1)-(q-1),0) # Make sure its not negative
num_qgram2 = max(len(str2)-(q-1),0)
# Check if there are q-grams at all from both strings - - - - - - - - - - - -
# (no q-grams if length of a string is less than q)
#
if ((padded == False) and (min(num_qgram1, num_qgram2) == 0)):
return 0.0
# Calculate the divisor - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
if (common_divisor not in ['average','shortest','longest']):
logging.exception('Illegal value for common divisor: %s' % \
(common_divisor))
raise Exception
if (common_divisor == 'average'):
divisor = 0.5*(num_qgram1+num_qgram2) # Compute average number of q-grams
elif (common_divisor == 'shortest'):
divisor = min(num_qgram1,num_qgram2)
else: # Longest
divisor = max(num_qgram1,num_qgram2)
# Use number of q-grams to quickly check for minimum threshold - - - - - - -
#
if (min_threshold != None):
if (isinstance(min_threshold, float)) and (min_threshold > 0.0) and \
(min_threshold > 0.0):
max_common_qgram = min(num_qgram1,num_qgram2)
w = float(max_common_qgram) / float(divisor)
if (w < min_threshold):
return 0.0 # Similariy is smaller than minimum threshold
else:
logging.exception('Illegal value for minimum threshold (not between' + \
' 0 and 1): %f' % (min_threshold))
raise Exception
# Add start and end characters (padding) - - - - - - - - - - - - - - - - - -
#
if (padded == True):
qgram_str1 = (q-1)*QGRAM_START_CHAR+str1+(q-1)*QGRAM_END_CHAR
qgram_str2 = (q-1)*QGRAM_START_CHAR+str2+(q-1)*QGRAM_END_CHAR
else:
qgram_str1 = str1
qgram_str2 = str2
# Make a list of q-grams for both strings - - - - - - - - - - - - - - - - - -
#
qgram_list1 = [qgram_str1[i:i+q] for i in range(len(qgram_str1) - (q-1))]
qgram_list2 = [qgram_str2[i:i+q] for i in range(len(qgram_str2) - (q-1))]
# Get common q-grams - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
common = 0
if (num_qgram1 < num_qgram2): # Count using the shorter q-gram list
short_qgram_list = qgram_list1
long_qgram_list = qgram_list2
else:
short_qgram_list = qgram_list2
long_qgram_list = qgram_list1
for q_gram in short_qgram_list:
if (q_gram in long_qgram_list):
common += 1
long_qgram_list.remove(q_gram) # Remove the counted q-gram
w = float(common) / float(divisor)
assert (w >= 0.0) and (w <= 1.0), 'Similarity weight outside 0-1: %f' % (w)
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('%d-gram comparator string "%s" with "%s" value: %.3f' % \
(q, str1, str2, w))
return w
# =============================================================================
def bigram(str1, str2, min_threshold = None):
"""For backwards compatibility.
"""
return qgram(str1, str2, 2, 'average', min_threshold)
# =============================================================================
def posqgram(str1, str2, q=2, max_dist = 2, common_divisor = 'average',
min_threshold = None, padded=True):
"""Return approximate string comparator measure (between 0.0 and 1.0)
using positional q-grams (with default bigrams: q = 2).
USAGE:
score = posqgram(str1, str2, q, max_dist, common_divisor, min_threshold,
padded)
ARGUMENTS:
str1 The first string
str2 The second string
q The length of the q-grams to be used. Must be at least 1.
max_dist Maximum distance allowed between two positional q-grams
(for example, with max_dist = 2 ('pe',6) and ('pe',8) are
considered to be similar, however, ('pe',1) and ('pe',7)
are not).
common_divisor Method of how to calculate the divisor, it can be set to
'average','shortest', or 'longest' , and is calculated
according to the lengths of the two input strings
min_threshold Minimum threshold between 0 and 1
padded If set to True (default), the beginnng and end of the
strings will be padded with (q-1) special characters, if
False no padding will be done.
DESCRIPTION:
q-grams are q-character sub-strings contained in a string. For example,
'peter' contains the bigrams (q=2): ['pe','et','te','er'].
Positional q-grams also contain the position within the string:
[('pe',0),('et',1),('te',2),('er',3)].
Padding will result in specific q-grams at the beginning and end of a
string, for example 'peter' converted into padded bigrams (q=2) will result
in the following 2-gram list:
[('*p',0),('pe',1),('et',2),('te',3),('er',4),('r@',5)], with '*'
illustrating the start and '@' the end character.
This routine counts the number of common q-grams within the maximum
distance and divides by the average number of q-grams. The resulting number
is returned.
"""
if (q < 1):
logging.exception('Illegal value for q: %d (must be at least 1)' % (q))
raise Exception
if (max_dist < 0):
logging.exception('Illegal value for maximum distance:: %d (must be ' % \
(max_dist) + 'zero or positive)')
raise Exception
# Quick check if the strings are empty or the same - - - - - - - - - - - - -
#
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
# Calculate number of q-grams in strings (plus start and end characters) - -
#
if (padded == True):
num_qgram1 = len(str1)+q-1
num_qgram2 = len(str2)+q-1
else:
num_qgram1 = max(len(str1)-(q-1),0) # Make sure its not negative
num_qgram2 = max(len(str2)-(q-1),0)
# Check if there are q-grams at all from both strings - - - - - - - - - - - -
# (no q-grams if length of a string is less than q)
#
if ((padded == False) and (min(num_qgram1, num_qgram2) == 0)):
return 0.0
# Calculate the divisor - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
if (common_divisor not in ['average','shortest','longest']):
logging.exception('Illegal value for common divisor: %s' % \
(common_divisor))
raise Exception
if (common_divisor == 'average'):
divisor = 0.5*(num_qgram1+num_qgram2) # Compute average number of q-grams
elif (common_divisor == 'shortest'):
divisor = min(num_qgram1,num_qgram2)
else: # Longest
divisor = max(num_qgram1,num_qgram2)
# Use number of q-grams to quickly check for minimum threshold - - - - - - -
#
if (min_threshold != None):
if (isinstance(min_threshold, float)) and (min_threshold > 0.0) and \
(min_threshold > 0.0):
max_common_qgram = min(num_qgram1,num_qgram2)
w = float(max_common_qgram) / float(divisor)
if (w < min_threshold):
return 0.0 # Similariy is smaller than minimum threshold
else:
logging.exception('Illegal value for minimum threshold (not between' + \
' 0 and 1): %f' % (min_threshold))
raise Exception
# Add start and end characters (padding) - - - - - - - - - - - - - - - - - -
#
if (padded == True):
qgram_str1 = (q-1)*QGRAM_START_CHAR+str1+(q-1)*QGRAM_END_CHAR
qgram_str2 = (q-1)*QGRAM_START_CHAR+str2+(q-1)*QGRAM_END_CHAR
else:
qgram_str1 = str1
qgram_str2 = str2
# Make a list of q-grams for both strings - - - - - - - - - - - - - - - - - -
#
qgram_list1 = [(qgram_str1[i:i+q],i) for i in range(len(qgram_str1) - (q-1))]
qgram_list2 = [(qgram_str2[i:i+q],i) for i in range(len(qgram_str2) - (q-1))]
# Get common q-grams - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
common = 0
if (num_qgram1 < num_qgram2): # Count using the shorter q-gram list
short_qgram_list = qgram_list1
long_qgram_list = qgram_list2
else:
short_qgram_list = qgram_list2
long_qgram_list = qgram_list1
for pos_q_gram in short_qgram_list:
(q_gram,pos) = pos_q_gram
pos_range = range(max(pos-max_dist,0), pos+max_dist+1)
for test_pos in pos_range:
test_pos_q_gram = (q_gram,test_pos)
if (test_pos_q_gram in long_qgram_list):
common += 1
long_qgram_list.remove(test_pos_q_gram) # Remove the counted q-gram
break
w = float(common) / float(divisor)
assert (w >= 0.0) and (w <= 1.0), 'Similarity weight outside 0-1: %f' % (w)
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Positional %d-gram (max distance=%d) comparator string ' % \
(q,max_dist) + '"%s" with "%s" value: %.3f' % (str1, str2, w))
return w
# =============================================================================
def sgram(str1, str2, gc, common_divisor = 'average', min_threshold = None,
padded=True):
"""Return approximate string comparator measure (between 0.0 and 1.0)
using s-grams (skip-grams) with bigrams.
USAGE:
score = sgram(str1, str2, gc, common_divisor, min_threshold, padded)
ARGUMENTS:
str1 The first string
str2 The second string
gc Gram class list (see below).
common_divisor Method of how to calculate the divisor, it can be set to
'average','shortest', or 'longest' , and is calculated
according to the lengths of the two input strings
min_threshold Minimum threshold between 0 and 1
padded If set to True (default), the beginnng and end of the
strings will be padded with (q-1) special characters, if
False no padding will be done.
DESCRIPTION:
Uses s-grams as described in:
"Non-adjacent Digrams Improve Matching of Cross-Lingual Spelling Variants"
by H. Keskustalo, A. Pirkola, K. Visala, E. Leppanen and J. Jarvelin,
SPIRE 2003.
Padding will result in special start and end characters being added at the
beginning and the end of the character, similar to as done for the qgram
and posqgram routines.
"""
# Quick check if the strings are empty or the same - - - - - - - - - - - - -
#
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
# Check if divisor is OK - - - - - - - - - - - - - - - - - - - - - - - - - -
#
if (common_divisor not in ['average','shortest','longest']):
logging.exception('Illegal value for common divisor: %s' % \
(common_divisor))
raise Exception
# Extend strings with start and end characters
#
if (padded == True):
tmp_str1 = QGRAM_START_CHAR+str1+QGRAM_END_CHAR
tmp_str2 = QGRAM_START_CHAR+str2+QGRAM_END_CHAR
else:
tmp_str1 = str1
tmp_str2 = str2
len1 = len(tmp_str1)
len2 = len(tmp_str2)
common = 0.0 # Sum number of common s-grams over gram classes
divisor = 0.0 # Sum of divisors over gram classes
# Loop over all gram classes given - - - - - - - - - - - - - - - - - - - - -
#
for c in gc:
sgram_list1 = []
sgram_list2 = []
for s in c: # Skip distances
for i in range(0,len1-s-1):
sgram_list1.append(tmp_str1[i]+tmp_str1[i+s+1])
for i in range(0,len2-s-1):
sgram_list2.append(tmp_str2[i]+tmp_str2[i+s+1])
num_sgram1 = len(sgram_list1)
num_sgram2 = len(sgram_list2)
if (common_divisor == 'average'):
this_divisor = 0.5*(num_sgram1+num_sgram2) # Average number of s-grams
elif (common_divisor == 'shortest'):
this_divisor = min(num_sgram1,num_sgram2)
else: # Longest
this_divisor = max(num_sgram1,num_sgram2)
if (num_sgram1 < num_sgram2): # Count using the shorter s-gram list
short_sgram_list = sgram_list1
long_sgram_list = sgram_list2
else:
short_sgram_list = sgram_list2
long_sgram_list = sgram_list1
this_common = 0 # Number of common s-grams for this gram class
for s_gram in short_sgram_list:
if (s_gram in long_sgram_list):
this_common += 1
long_sgram_list.remove(s_gram) # Remove the counted s-gram
common += this_common
divisor += this_divisor
if (divisor == 0): # One string did not have any s-grams
w = 0.0
else:
w = common / divisor
assert (w >= 0.0) and (w <= 1.0), 'Similarity weight outside 0-1: %f' % (w)
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('s-gram comparator string "%s" with "%s" value: %.3f' % \
(str1, str2, w))
return w
# =============================================================================
def editdist(str1, str2, min_threshold = None):
"""Return approximate string comparator measure (between 0.0 and 1.0)
using the edit (or Levenshtein) distance.
USAGE:
score = editdist(str1, str2, min_threshold)
ARGUMENTS:
str1 The first string
str2 The second string
min_threshold Minimum threshold between 0 and 1
DESCRIPTION:
The edit distance is the minimal number of insertions, deletions and
substitutions needed to make two strings equal.
For more information on the modified Soundex see:
- http://www.nist.gov/dads/HTML/editdistance.html
"""
# Quick check if the strings are empty or the same - - - - - - - - - - - - -
#
if (str1 == '') or (str2 == ''):
return 0.0
elif (str1 == str2):
return 1.0
n = len(str1)
m = len(str2)
max_len = max(n,m)
if (min_threshold != None):
if (isinstance(min_threshold, float)) and (min_threshold > 0.0) and \
(min_threshold > 0.0):
len_diff = abs(n-m)
w = 1.0 - float(len_diff) / float(max_len)
if (w < min_threshold):
return 0.0 # Similariy is smaller than minimum threshold
else: # Calculate the maximum distance possible with this threshold
max_dist = (1.0-min_threshold)*max_len
else:
logging.exception('Illegal value for minimum threshold (not between' + \
' 0 and 1): %f' % (min_threshold))
raise Exception