forked from J535D165/FEBRL-fork-v0.4.2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
encode.py
1977 lines (1704 loc) · 65.2 KB
/
encode.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: "encode.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 encode.py - Various phonetic name encoding methods.
Encoding methods provided:
soundex Soundex
mod_soundex Modified Soundex
phonex Phonex
nysiis NYSIIS
dmetaphone Double-Metaphone
phonix Phonix
fuzzy_soundex Fuzzy Soundex based on q-gram substitutions and letter
encodings
get_substring Simple function which extracts and returns a sub-string
freq_vector Count characters and put into a vector
See doc strings of individual routines for detailed documentation.
There is also a routine called 'phonix_transform' which only performs the
Phonix string transformation without the final numerical encoding. This can
be useful for approximate string comparison functions.
Note that all encoding routines assume the input string only contains letters
and whitespaces, but not digits or other ASCII characters.
If called from the command line, a test routine is run which prints example
encodings for various strings.
"""
# =============================================================================
# Imports go here
import logging
import string
import time
# =============================================================================
def do_encode(encode_method, in_str):
"""A 'chooser' functions which performs the selected string encoding method.
For each encoding method, two calling versions are provided. One limiting the
length of the code to 4 characters (and possibly pads shorter codes with a
fill character, for example '0' for soundex), the other returning an
unlimited length code.
Possible values for 'encode_method' are:
soundex Unlimited length Soundex encoding
soundex4 Soundex limited/padded to length 4
mod_soundex Modified unlimited length Soundex encoding
mod_soundex4 Modified Soundex limited/padded to length 4
phonex Unlimited length Phonex encoding
phonex4 Phonex limited/padded to length 4
phonix Unlimited length Phonix encoding
phonix4 Phonix limited/padded to length 4
phonix_transform Only perform Phonix string transformation without
numerical encoding
nysiis Unlimited length NYSIIS encoding
nysiis4 NYSIIS limited/padded to length 4
dmetaphone Unlimited length Double-Metaphone encoding
dmetaphone4 Double-Metaphone limited/padded to length 4
fuzzy_soundex Fuzzy Soundex
fuzzy_soundex4 Fuzzy Soundex limited/padded to length 4
This functions returns the phonetic code as well as the time needed to
generate it (as floating-point value in seconds).
"""
if (encode_method[-1] == '4'):
maxlen = 4
else:
maxlen = -1
if (encode_method.startswith('soundex')):
start_time = time.time()
phonetic_code = soundex(in_str, maxlen)
time_used = time.time() - start_time
elif (encode_method.startswith('mod_soundex')):
start_time = time.time()
phonetic_code = mod_soundex(in_str, maxlen)
time_used = time.time() - start_time
elif (encode_method.startswith('phonex')):
start_time = time.time()
phonetic_code = phonex(in_str, maxlen)
time_used = time.time() - start_time
elif (encode_method.startswith('phonix_transform')):
start_time = time.time()
phonetic_code = phonix_transform(in_str)
time_used = time.time() - start_time
elif (encode_method.startswith('phonix')):
start_time = time.time()
phonetic_code = phonix(in_str, maxlen)
time_used = time.time() - start_time
elif (encode_method.startswith('nysiis')):
start_time = time.time()
phonetic_code = nysiis(in_str, maxlen)
time_used = time.time() - start_time
elif (encode_method.startswith('dmetaphone')):
start_time = time.time()
phonetic_code = dmetaphone(in_str, maxlen)
time_used = time.time() - start_time
elif (encode_method.startswith('fuzzy_soundex')):
start_time = time.time()
phonetic_code = fuzzy_soundex(in_str, maxlen)
time_used = time.time() - start_time
else:
logging.exception('Illegal string encoding method: %s' % (encode_method))
raise Exception
return phonetic_code, time_used
# =============================================================================
def soundex(s, maxlen=4):
"""Compute the soundex code for a string.
USAGE:
code = soundex(s, maxlen)
ARGUMENTS:
s A string containing a name.
maxlen Maximal length of the returned code. If a code is longer than
'maxlen' it is truncated. Default value is 4.
If 'maxlen' is negative the soundex code will not be padded with
'0' to 'maxlen' characters.
DESCRIPTION:
For more information on Soundex see:
- http://www.bluepoof.com/Soundex/info.html
- http://www.nist.gov/dads/HTML/soundex.html
"""
if (not s):
if (maxlen > 0):
return maxlen*'0' # Or 'z000' for compatibility with other
# implementations
else:
return '0'
# Translation table and characters that will not be used for soundex - - - -
#
transtable = string.maketrans('abcdefghijklmnopqrstuvwxyz', \
'01230120022455012623010202')
# deletechars='aeiouhwy '
deletechars = ' '
s2 = string.translate(s[1:],transtable,deletechars)
s3 = s[0] # Keep first character of original string
# Only add numbers if they are not the same as the previous number
#
for i in s2:
if (i != s3[-1]):
s3 = s3+i
# Remove all '0'
s4 = s3.replace('0', '')
# Fill up with '0' to maxlen length
#
s4 = s4+maxlen*'0'
if (maxlen > 0):
resstr = s4[:maxlen] # Return first maxlen characters
else:
resstr = s4
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Soundex encoding for string: "%s": %s' % (s, resstr))
return resstr
# =============================================================================
def mod_soundex(s, maxlen=4):
"""Compute the modified soundex code for a string.
USAGE:
code = mod_soundex(s, maxlen)
ARGUMENTS:
s A string containing a name.
maxlen Maximal length of the returned code. If a code is longer than
'maxlen' it is truncated. Default value is 4.
If 'maxlen' is negative the soundex code will not be padded with
'0' to 'maxlen' characters.
DESCRIPTION:
For more information on the modified Soundex see:
- http://www.bluepoof.com/Soundex/info2.html
"""
# Translation table and characters that will not be used for soundex - - - -
#
transtable = string.maketrans('abcdefghijklmnopqrstuvwxyz', \
'01360240043788015936020505')
deletechars='aeiouhwy '
if (not s):
if (maxlen > 0):
return maxlen*'0' # Or 'z000' for compatibility with other
# implementations
else:
return '0'
s2 = string.translate(s[1:],transtable, deletechars)
s3 = s[0] # Keep first character of original string
# Only add numbers if they are not the same as the previous number
for i in s2:
if (i != s3[-1]):
s3 = s3+i
# Fill up with '0' to maxlen length
#
s4 = s3+maxlen*'0'
if (maxlen > 0):
resstr = s4[:maxlen] # Return first maxlen characters
else:
resstr = s4
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Mod Soundex encoding for string: "%s": %s' % (s, resstr))
return resstr
# =============================================================================
def phonex(s, maxlen=4):
"""Compute the phonex code for a string.
USAGE:
code = phonex(s, maxlen)
ARGUMENTS:
s A string containing a name.
maxlen Maximal length of the returned code. If a code is longer than
'maxlen' it is truncated. Default value is 4.
If 'maxlen' is negative the soundex code will not be padded with
'0' to 'maxlen' characters.
DESCRIPTION:
Based on the algorithm as described in:
"An Assessment of Name Matching Algorithms, A.J. Lait and B. Randell,
Technical Report number 550, Department of Computing Science,
University of Newcastle upon Tyne, 1996"
Available at:
http://www.cs.ncl.ac.uk/~brian.randell/home.informal/
Genealogy/NameMatching.pdf
Bug-fixes regarding 'h','ss','hss' etc. strings thanks to Marion Sturtevant
"""
if (not s):
if (maxlen > 0):
return maxlen*'0' # Or 'z000' for compatibility with other
# implementations
else:
return '0'
# Preprocess input string - - - - - - - - - - - - - - - - - - - - - - - - - -
#
while (s and s[-1] == 's'): # Remove all 's' at the end
s = s[:-1]
if (not s):
if (maxlen > 0):
return maxlen*'0' # Or 'z000' for compatibility with other
# implementations
else:
return '0'
if (s[:2] == 'kn'): # Remove 'k' from beginning if followed by 'n'
s = s[1:]
elif (s[:2] == 'ph'): # Replace 'ph' at beginning with 'f'
s = 'f'+s[2:]
elif (s[:2] == 'wr'): # Remove 'w' from beginning if followed by 'r'
s = s[1:]
if (s[0] == 'h'): # Remove 'h' from beginning
s = s[1:]
if (not s):
if (maxlen > 0):
return maxlen*'0' # Or 'z000' for compatibility with other
# implementations
else:
return '0'
# Make phonetic equivalence of first character
#
if (s[0] in 'eiouy'):
s = 'a'+s[1:]
elif (s[0] == 'p'):
s = 'b'+s[1:]
elif (s[0] == 'v'):
s = 'f'+s[1:]
if (s[0] in 'kq'):
s = 'c'+s[1:]
elif (s[0] == 'j'):
s = 'g'+s[1:]
elif (s[0] == 'z'):
s = 's'+s[1:]
# Modified soundex coding - - - - - - - - - - - - - - - - - - - - - - - - - -
#
s_len = len(s)
code = '' # Phonex code
i = 0
while (i < s_len): # Loop over all characters in s
s_i = s[i]
code_i = '0' # Default code
if (s_i in 'bfpv'):
code_i = '1'
elif (s_i in 'cskgjqxz'):
code_i = '2'
elif (s_i in 'dt') and (i < s_len-1) and (s[i+1] != 'c'):
code_i = '3'
elif (s_i == 'l') and ((i == s_len-1) or \
((i < s_len-1) and (s[i+1] in 'aeiouy'))):
code_i = '4'
elif (s_i in 'mn'):
code_i = '5'
if (i < s_len-1) and (s[i+1] in 'dg'):
s = s[:i+1]+s_i+s[i+2:] # Replace following D or G with current M or N
elif (s_i == 'r') and ((i == s_len-1) or \
((i < s_len-1) and (s[i+1] in 'aeiouy'))):
code_i = '6'
if (i == 0): # Handle beginning of string
last = code_i
code += s_i # Start code with a letter
else:
if (code_i != last) and (code_i != '0'):
# If the code differs from previous code and it's not a vowel code
#
code += code_i
last = code[-1]
i += 1
# Fill up with '0' to maxlen length
#
code += maxlen*'0'
if (maxlen > 0):
resstr = code[:maxlen] # Return first maxlen characters
else:
resstr = code
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Phonex encoding for string: "%s": %s' % (s, resstr))
return resstr
# =============================================================================
def phonix(s, maxlen=4):
"""Compute the phonix code for a string.
USAGE:
code = phonix(s, maxlen)
ARGUMENTS:
s A string containing a name.
maxlen Maximal length of the returned code. If a code is longer than
'maxlen' it is truncated. Default value is 4.
If 'maxlen' is negative the soundex code will not be padded with
'0' to 'maxlen' characters.
DESCRIPTION:
Based on the Phonix implementation from Ulrich Pfeifer's WAIS, see:
http://search.cpan.org/src/ULPFR/WAIT-1.800/
For more information on Phonix see:
"PHONIX: The algorithm", Program: automated library and information
systems, 24(4),363-366, 1990, by T. Gadd
"""
if (not s):
if (maxlen > 0):
return 'a'+(maxlen-1)*'0'
else:
return ''
# First apply Phonix transformation
#
phonixstr = phonix_transform(s)
if (phonixstr == ''):
if (maxlen > 0):
return 'a'+(maxlen-1)*'0'
else:
return ''
# Translation table and characters that will not be used for Phonix
#
transtable = string.maketrans('abcdefghijklmnopqrstuvwxyz', \
'01230720022455012683070808')
# deletechars='aeiouhwy '
deletechars = ' '
s2 = string.translate(phonixstr[1:],transtable,deletechars)
# If first character is a vowel or 'y' replace it with 'V' otherwise keep it
# (assume all other characters are lowercase)
#
if (phonixstr[0] in 'aeiouy'):
s3 = 'V' # Different from lowercase 'v'
else:
s3 = phonixstr[0]
# Only add numbers if they are not the same as the previous number
#
for i in s2:
if (i != s3[-1]):
s3 = s3+i
# Remove all '0'
s4 = s3.replace('0', '')
# Fill up with '0' to maxlen length
#
s4 = s4+maxlen*'0'
if (maxlen > 0):
resstr = s4[:maxlen] # Return first maxlen characters
else:
resstr = s4
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Phonix encoding for string: "%s": %s' % (s, resstr))
return resstr
# =============================================================================
def phonix_transform(s):
"""Do Phonix transformation for a string.
USAGE:
phonixstr = phonix_transform(s, maxlen)
ARGUMENTS:
s A string containing a name.
DESCRIPTION:
This function only does the Phonix transformation of the given input string
without the final numerical encoding.
Based on the Phonix implementation from Ulrich Pfeifer's WAIS, see:
http://search.cpan.org/src/ULPFR/WAIT-1.800/
For more information on Phonix see:
"PHONIX: The algorithm", Program: automated library and information
systems, 24(4),363-366, 1990, by T. Gadd
"""
if (s == ''):
return s
# Function which replaces a pattern in a string - - - - - - - - - - - - - - -
# - where can be one of: 'ALL','START','END','MIDDLE'
# - Pre-condition (default None) can be 'V' for vowel or 'C' for consonant
# - Post-condition (default None) can be 'V' for vowel or 'C' for consonant
#
def phonix_replace(s, where, orgpat, newpat, precond, postcond):
vowels = 'aeiouy'
tmpstr = s
start_search = 0 # Position from where to start the search
pat_len = len(orgpat)
while (orgpat in tmpstr[start_search:]): # As long as pattern is in string
pat_start = tmpstr.find(orgpat,start_search)
str_len = len(tmpstr)
# Check conditions of previous and following character
#
OKpre = False # Previous character condition
OKpost = False # Following character condition
if (precond == None):
OKpre = True
elif (pat_start > 0):
if (((precond == 'V') and (tmpstr[pat_start-1] in vowels)) or \
((precond == 'C') and (tmpstr[pat_start-1] not in vowels))):
OKpre = True
if (postcond == None):
OKpost = True
else:
pat_end = pat_start+pat_len
if (pat_end < str_len):
if (((postcond == 'V') and (tmpstr[pat_end] in vowels)) or \
((postcond == 'C') and (tmpstr[pat_end] not in vowels))):
OKpost = True
# Replace pattern if conditions and position OK
#
if ((OKpre == True) and (OKpost == True)) and \
(((where == 'START') and (pat_start == 0)) or \
((where == 'MIDDLE') and (pat_start > 0) and \
(pat_start+pat_len < str_len)) or \
((where == 'END') and (pat_start+pat_len == str_len)) or \
(where == 'ALL')):
tmpstr = tmpstr[:pat_start]+newpat+tmpstr[pat_start+pat_len:]
start_search = pat_start
else:
#start_search += 1
start_search = pat_start+1
return tmpstr
# Replacement table according to Gadd's definition - - - - - - - - - - - - -
#
replace_table = [('ALL', 'dg', 'g'),
('ALL', 'co', 'ko'),
('ALL', 'ca', 'ka'),
('ALL', 'cu', 'ku'),
('ALL', 'cy', 'si'),
('ALL', 'ci', 'si'),
('ALL', 'ce', 'se'),
('START', 'cl', 'kl', None, 'V'),
('ALL', 'ck', 'k'),
('END', 'gc', 'k'),
('END', 'jc', 'k'),
('START', 'chr', 'kr', None, 'V'),
('START', 'cr', 'kr', None, 'V'),
('START', 'wr', 'r'),
('ALL', 'nc', 'nk'),
('ALL', 'ct', 'kt'),
('ALL', 'ph', 'f'),
('ALL', 'aa', 'ar'),
('ALL', 'sch', 'sh'),
('ALL', 'btl', 'tl'),
('ALL', 'ght', 't'),
('ALL', 'augh', 'arf'),
('MIDDLE', 'lj', 'ld', 'V', 'V'),
('ALL', 'lough', 'low'),
('START', 'q', 'kw'),
('START', 'kn', 'n'),
('END', 'gn', 'n'),
('ALL', 'ghn', 'n'),
('END', 'gne', 'n'),
('ALL', 'ghne', 'ne'),
('END', 'gnes', 'ns'),
('START', 'gn', 'n'),
('MIDDLE', 'gn', 'n', None, 'C'),
('END', 'gn', 'n'), # None, 'C'
('START', 'ps', 's'),
('START', 'pt', 't'),
('START', 'cz', 'c'),
('MIDDLE', 'wz', 'z', 'V', None),
('MIDDLE', 'cz', 'ch'),
('ALL', 'lz', 'lsh'),
('ALL', 'rz', 'rsh'),
('MIDDLE', 'z', 's', None, 'V'),
('ALL', 'zz', 'ts'),
('MIDDLE', 'z', 'ts', 'C', None),
('ALL', 'hroug', 'rew'),
('ALL', 'ough', 'of'),
('MIDDLE', 'q', 'kw', 'V', 'V'),
('MIDDLE', 'j', 'y', 'V', 'V'),
('START', 'yj', 'y', None, 'V'),
('START', 'gh', 'g'),
# ('END', 'e', 'gh', 'V', None), # Wrong in Pfeifer
('END', 'gh', 'e', 'V', None), # From Zobel code
('START', 'cy', 's'),
('ALL', 'nx', 'nks'),
('START', 'pf', 'f'),
('END', 'dt', 't'),
('END', 'tl', 'til'),
('END', 'dl', 'dil'),
('ALL', 'yth', 'ith'),
('START', 'tj', 'ch', None, 'V'),
('START', 'tsj', 'ch', None, 'V'),
('START', 'ts', 't', None, 'V'),
('ALL', 'tch', 'ch'), # Wrong funct call in Pfeifer
('MIDDLE', 'wsk', 'vskie', 'V', None),
('END', 'wsk', 'vskie', 'V', None),
('START', 'mn', 'n', None, 'V'),
('START', 'pn', 'n', None, 'V'),
('MIDDLE', 'stl', 'sl', 'V', None),
('END', 'stl', 'sl', 'V', None),
('END', 'tnt', 'ent'),
('END', 'eaux', 'oh'),
('ALL', 'exci', 'ecs'),
('ALL', 'x', 'ecs'),
('END', 'ned', 'nd'),
('ALL', 'jr', 'dr'),
('END', 'ee', 'ea'),
('ALL', 'zs', 's'),
('MIDDLE', 'r', 'ah', 'V', 'C'),
('END', 'r', 'ah', 'V', None), # 'V', 'C'
('MIDDLE', 'hr', 'ah', 'V', 'C'),
('END', 'hr', 'ah', 'V', None), # 'V', 'C'
('END', 'hr', 'ah', 'V', None),
('END', 're', 'ar'),
('END', 'r', 'ah', 'V', None),
('ALL', 'lle', 'le'),
('END', 'le', 'ile', 'C', None),
('END', 'les', 'iles', 'C', None),
('END', 'e', ''),
('END', 'es', 's'),
('END', 'ss', 'as', 'V', None),
('END', 'mb', 'm', 'V', None),
('ALL', 'mpts', 'mps'),
('ALL', 'mps', 'ms'),
('ALL', 'mpt', 'mt')]
workstr = s
for rtpl in replace_table: # Check all transformations in the table
if (len(rtpl) == 3):
rtpl += (None,None)
workstr = phonix_replace(workstr,rtpl[0],rtpl[1],rtpl[2],rtpl[3],rtpl[4])
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('Phonix transformation: "%s" into "%s"' % (s, workstr))
return workstr
# =============================================================================
def nysiis(s, maxlen=4):
"""Compute the NYSIIS code for a string.
USAGE:
code = nysiis(s, maxlen)
ARGUMENTS:
s A string containing a name.
maxlen Maximal length of the returned code. If a code is longer than
'maxlen' it is truncated. Default value is 4.
If 'maxlen' is negative the soundex code will not be padded with
'0' to 'maxlen' characters.
DESCRIPTION:
For more information on NYSIIS see:
- http://www.dropby.com/indexLF.html?content=/NYSIIS.html
- http://www.nist.gov/dads/HTML/nysiis.html
"""
if (not s):
return ''
# Remove trailing S or Z
#
while s and s[-1] in 'sz':
s = s[:-1]
# Translate first characters of string
#
if (s[:3] == 'mac'): # Initial 'MAC' -> 'MC'
s = 'mc'+s[3:]
elif (s[:2] == 'pf'): # Initial 'PF' -> 'F'
s = s[1:]
# Translate some suffix characters:
#
suff_dict = {'ix':'ic', 'ex':'ec', 'ye':'y', 'ee':'y', 'ie':'y', \
'dt':'d', 'rt':'d', 'rd':'d', 'nt':'n', 'nd':'n'}
suff = s[-2:]
s = s[:-2]+suff_dict.get(suff, suff) # Replace suffix if in dictionary
# Replace EV with EF
#
if (s[2:].find('ev') > -1):
s = s[:-2]+s[2:].replace('ev','ef')
if (not s):
return ''
first = s[0] # Save first letter for final code
# Replace all vowels with A and delete whitespaces
#
voweltable = string.maketrans('eiou', 'aaaa')
s2 = string.translate(s,voweltable, ' ')
if (not s2): # String only contained whitespaces
return ''
# Remove all W that follow an A
#
s2 = s2.replace('aw','a')
# Various replacement patterns
#
s2 = s2.replace('ght','gt')
s2 = s2.replace('dg','g')
s2 = s2.replace('ph','f')
s2 = s2[0]+s2[1:].replace('ah','a')
s3 = s2[0]+s2[1:].replace('ha','a')
s3 = s3.replace('kn','n')
s3 = s3.replace('k','c')
s4 = s3[0]+s3[1:].replace('m','n')
s5 = s4[0]+s4[1:].replace('q','g')
s5 = s5.replace('sh','s')
s5 = s5.replace('sch','s')
s5 = s5.replace('yw','y')
s5 = s5.replace('wr','r')
# If not first or last, replace Y with A
#
s6 = s5[0]+s5[1:-1].replace('y','a')+s5[-1]
# If not first character, replace Z with S
#
s7 = s6[0]+s6[1:].replace('z','s')
# Replace trailing AY with Y
#
if (s7[-2:] == 'ay'):
s7 = s7[:-2]+'y'
# Remove trailing vowels (now only A)
#
while s7 and s7[-1] == 'a':
s7 = s7[:-1]
if (len(s7) == 0):
resstr = ''
else:
resstr = s7[0]
# Only add letters if they differ from the previous letter
#
for i in s7[1:]:
if (i != resstr[-1]):
resstr=resstr+i
# Now compile final result string
#
if (first in 'aeiou'):
resstr = first+resstr[1:]
if (maxlen > 0):
resstr = resstr[:maxlen] # Return first maxlen characters
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.debug('NYSIIS encoding for string: "%s": %s' % (s, resstr))
return resstr
# =============================================================================
def dmetaphone(s, maxlen=4):
"""Compute the Double Metaphone code for a string.
USAGE:
code = dmetaphone(s, maxlen)
ARGUMENTS:
s A string containing a name.
maxlen Maximal length of the returned code. If a code is longer than
'maxlen' it is truncated. Default value is 4.
DESCRIPTION:
Based on:
- Lawrence Philips C++ code as published in C/C++ Users Journal (June 2000)
and available at:
http://www.cuj.com/articles/2000/0006/0006d/0006d.htm
- Perl/C implementation
http://www.cpan.org/modules/by-authors/id/MAURICE/
See also:
- http://aspell.sourceforge.net/metaphone/
- http://www.nist.gov/dads/HTML/doubleMetaphone.html
"""
if (not s):
return ''
primary = ''
secondary = ''
alternate = ''
primary_len = 0
secondary_len = 0
# Sub routines - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
def isvowel(c):
if (c in 'aeiouy'):
return 1
else:
return 0
def slavogermanic(str):
if (str.find('w')>-1) or (str.find('k')>-1) or (str.find('cz')>-1) or \
(str.find('witz')>-1):
return 1
else:
return 0
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
length = len(s)
if (len < 1):
return ''
last = length-1
current = 0 # Current position in string
workstr = s+' '
if (workstr[0:2] in ['gn','kn','pn','wr','ps']):
current = current+1 # Skip first character
if (workstr[0] == 'x'): # Initial 'x' is pronounced like 's'
primary = primary+'s'
primary_len = primary_len+1
secondary = secondary+'s'
secondary_len = secondary_len+1
current = current+1
if (maxlen < 1): # Calculate maximum length to check
check_maxlen = length
else:
check_maxlen = maxlen
while (primary_len < check_maxlen) or (secondary_len < check_maxlen):
if (current >= length):
break
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Main loop, analyse current character
#
c = workstr[current]
if (c in 'aeiouy'):
if (current == 0): # All initial vowels map to 'a'
primary = primary+'a'
primary_len = primary_len+1
secondary = secondary+'a'
secondary_len = secondary_len+1
current=current+1
elif (c == 'b'): # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
primary = primary+'p'
primary_len = primary_len+1
secondary = secondary+'p'
secondary_len = secondary_len+1
if (workstr[current+1] == 'b'):
current=current+2
else:
current=current+1
# elif (s == 'c'): # C
# primary = primary+'s'
# primary_len = primary_len+1
# secondary = secondary+'s'
# secondary_len = secondary_len+1
# current = current+1
elif (c == 'c'): # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if (current > 1) and (not isvowel(workstr[current-2])) and \
workstr[current-1:current+2] == 'ach' and \
(workstr[current+2] != 'i' and \
(workstr[current+2] != 'e' or \
workstr[current-2:current+4] in ['bacher','macher'])):
primary = primary+'k' # Various germanic special cases
primary_len = primary_len+1
secondary = secondary+'k'
secondary_len = secondary_len+1
current = current+2
elif (current == 0) and (workstr[0:6] == 'caesar'):
primary = primary+'s'
primary_len = primary_len+1
secondary = secondary+'s'
secondary_len = secondary_len+1
current = current+2
elif (workstr[current:current+4] == 'chia'): # Italian 'chianti'
primary = primary+'k'
primary_len = primary_len+1
secondary = secondary+'k'
secondary_len = secondary_len+1
current = current+2
elif (workstr[current:current+2] == 'ch'):
if (current > 0) and (workstr[current:current+4] == 'chae'):
primary = primary+'k' # Find 'michael'
primary_len = primary_len+1
secondary = secondary+'x'
secondary_len = secondary_len+1
current = current+2
elif (current == 0) and \
(workstr[current+1:current+6] in ['harac','haris'] or \
workstr[current+1:current+4] in \
['hor','hym','hia','hem']) and \
workstr[0:6] != 'chore':
primary = primary+'k' # Greek roots, eg. 'chemistry'
primary_len = primary_len+1
secondary = secondary+'k'
secondary_len = secondary_len+1
current = current+2
elif (workstr[0:4] in ['van ','von '] or \
workstr[0:3] == 'sch') or \
workstr[current-2:current+4] in \
['orches','archit','orchid'] or \
workstr[current+2] in ['t','s'] or \
((workstr[current-1] in ['a','o','u','e'] or \
current==0) and \
workstr[current+2] in \
['l','r','n','m','b','h','f','v','w',' ']):
primary = primary+'k'
primary_len = primary_len+1
secondary = secondary+'k'
secondary_len = secondary_len+1
current = current+2
else:
if (current > 0):
if (workstr[0:2] == 'mc'):
primary = primary+'k'
primary_len = primary_len+1
secondary = secondary+'k'
secondary_len = secondary_len+1
current = current+2
else:
primary = primary+'x'
primary_len = primary_len+1