forked from J535D165/FEBRL-fork-v0.4.2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
standardisation.py
2387 lines (1896 loc) · 95.1 KB
/
standardisation.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: "standardisation.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 standardisation.py - Classes for cleaning and standardisations.
This module provides classes for record cleaning and standardisations,
either based on rules or a machine learning approach (Hidden Markov models)
TODO
- PC 29/11/2002 Check for missing values in date fields (data standardiser)
And how to deal with them?
"""
# =============================================================================
# Import necessary modules (Python standard modules first, then Febrl modules)
import logging
import os
import string
import time
import auxiliary
import mymath
import phonenum
# =============================================================================
class RecordStandardiser:
"""Main class for the standardisation process. Implements a method to clean
and standardise all records in a data set.
A record standardiser will include one or more component standardisers.
Currently four different types of components can be standardised: names,
addresses, date and phone numbers. A list of component standardisers needs
to be given when a record standardiser is initialised.
A record standardiser needs the following instance variables to be set
when it is initialised:
input_dataset Reference to the input data set. Has to be initalised
in read access mode.
output_dataset Reference to the output data set. Has to be initalised
in write access mode.
comp_stand_list List with one or more component standardisers.
log_funct This can be a Python function or method which will log
(print or save to a file) a progress report message.
It is assumed that this function or method has one
input argument of type string (the message to be
printed). Default is None, in which case the normal
logging module will be used.
progress_report Can be set to a percentage number between 1 and 50 in
which case a progress report is logged during the
record pair comparison stage (in the run() method)
every selected percentage number. Default values is
10. If set to None no progress report will be logged.
pass_field_list A list of tuples (input_field, output_field) that will
simply be passed from the input data set to the output
data set without being cleaned or standardised. Each
input_field must be in the field list of the input
data set and correspondingly each output_filed in the
list of field of the output data set. Default value for
this argument is an empty list.
The standardise() method can be used to standardise all records from the
input data set and write them into the output data set.
"""
# ---------------------------------------------------------------------------
def __init__(self, **kwargs):
"""Constructor.
"""
self.description = ''
self.inp_dataset = None
self.out_dataset = None
self.comp_stand_list = [] # A list of one or more component standardiser
# tuples (each made of the component
# standardiser itself, a list with the field
# indices from the input data set, and a list
# of the field indices from the output data
# set. Only the standardisers themselves will
# be provided as input, the field index lists
# will be generated from them during
# initialisation.
self.progress_report = 10
self.log_funct = None
self.pass_field_list = []
# The indices of the pass fields into the input and output data sets
#
self.pass_field_index_list = []
# Process all keyword arguments
#
for (keyword, value) in kwargs.items():
if (keyword.startswith('desc')):
auxiliary.check_is_string('description', value)
self.description = value
elif (keyword.startswith('input_d')):
auxiliary.check_is_list('Input dataset field list', value.field_list)
self.in_dataset = value
elif (keyword.startswith('output_d')):
auxiliary.check_is_list('Output dataset field list', value.field_list)
self.out_dataset = value
elif (keyword.startswith('comp_stand')):
auxiliary.check_is_list('comp_stand_list', value)
self.comp_stand_list = value
elif (keyword.startswith('progr')):
if (value == None):
self.progress_report = value
else:
auxiliary.check_is_integer('progress_report', value)
if ((value < 1) or (value > 50)):
logging.exception('Illegal value for progress report, must be ' + \
'False or between 1 and 50: "%s"' % \
(str(value)))
raise Exception
self.progress_report = value
elif (keyword.startswith('log_f')):
auxiliary.check_is_function_or_method('log_funct', value)
self.log_funct = value
elif (keyword.startswith('pass_fi')):
auxiliary.check_is_list('pass_field_list', value)
self.pass_field_list = value
else:
logging.exception('Illegal constructor argument keyword: '+keyword)
raise Exception
# Check if the needed attributes are set - - - - - - - - - - - - - - - - -
#
auxiliary.check_is_not_none('Input dataset', self.in_dataset)
auxiliary.check_is_not_none('Output dataset', self.out_dataset)
auxiliary.check_is_not_none('Component standardiser list',
self.comp_stand_list)
if (self.in_dataset.access_mode != 'read'):
logging.exception('Input data set "%s" must be in "read" access mode' % \
(in_dataset.description))
raise Exception
if (self.out_dataset.access_mode != 'write'):
logging.exception('Output data set "%s" must be in "write" access ' % \
(out_dataset.description) + 'mode')
raise Exception
# Get a list of the fields from the input and output data sets
#
in_dataset_fields = []
for f_data in self.in_dataset.field_list:
in_dataset_fields.append(f_data[0]) # Append field name only
out_dataset_fields = []
for f_data in self.out_dataset.field_list:
out_dataset_fields.append(f_data[0])
# Check if there is no conflict in the output fields definition - - - - - -
#
output_fields_set = set()
for cs in self.comp_stand_list:
for field in cs.out_fields:
if (field != None): # Only check fields that are not set to None
if (field in output_fields_set):
logging.exception('Output fields definition conflict with ' + \
'field "%s"' % (str(field)))
raise Exception
output_fields_set.add(field)
# Check that fields in pass field list are in input and output data sets -
#
pass_out_field_set = set() # Check for duplicate output field names
i = 0
for field_tuple in self.pass_field_list:
auxiliary.check_is_tuple('pass_field_list[%d]' % (i), field_tuple)
if (len(field_tuple) != 2):
logging.exception('Field tuple in "pass_field_list" does not ' + \
'contain two fields: %s' % (str(field_tuple)))
raise Exception
in_field, out_field = field_tuple
if (in_field not in in_dataset_fields):
logging.exception('Input field in "pass_field_list" is not in the ' + \
'input data set: %s' % (str(field_tuple)))
raise Exception
if (out_field not in out_dataset_fields):
logging.exception('Output field in "pass_field_list" is not in the' + \
' output data set: %s' % (str(field_tuple)))
raise Exception
if (out_field in pass_out_field_set):
logging.exception('Output field in "pass_field_list" appears twice' + \
' field tuples: %s' % (str(self.pass_field_list)))
raise Exception
pass_out_field_set.add(out_field)
# Check for conflicts with component standardiser output fields
#
if (out_field in output_fields_set):
logging.exception('Output field in "pass_field_list" is also an ' + \
'output field of a component standardiser: %s' % \
(str(self.pass_field_list)))
raise Exception
in_pass_field_ind = in_dataset_fields.index(in_field)
out_pass_field_ind = out_dataset_fields.index(out_field)
self.pass_field_index_list.append((in_pass_field_ind,out_pass_field_ind))
i += 1
# Check all component standardisers and generate their lists of field - - -
# indices to be used.
#
for i in range(len(self.comp_stand_list)):
cs = self.comp_stand_list[i]
in_field_indices = []
in_not_none = 0
for in_f in cs.in_fields:
if (in_f != None):
in_not_none += 1
if in_f not in in_dataset_fields:
logging.exception('Component standardiser "%s" contains a ' % \
(cs.description) + 'field that is not in ' + \
'the input data set: %s' % (in_f))
raise Exception
in_field_indices.append(in_dataset_fields.index(in_f))
else:
in_field_indices.append(None)
if (in_not_none == 0):
logging.exception('No input field, or only None input fields ' + \
'defined for component standardiser "%s"' % \
(cs.description))
raise Exception
# Now the same for output fields
#
out_field_indices = []
out_not_none = 0
for out_f in cs.out_fields:
if (out_f != None):
out_not_none += 1
if out_f not in out_dataset_fields:
logging.exception('Component standardiser "%s" contains a ' % \
(cs.description) + 'field that is not in the' + \
' output data set: %s' % (out_f))
raise Exception
out_field_indices.append(out_dataset_fields.index(out_f))
else:
out_field_indices.append(None)
if (out_not_none == 0):
logging.exception('No output field, or only None output fields' + \
'defined for component standardiser "%s"' % \
(cs.description))
raise Exception
self.comp_stand_list[i] = (cs, in_field_indices, out_field_indices)
# A log message - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#
logging.info('Initialised record standardiser: %s' % (self.description))
logging.info(' Input data set: %s' % (self.in_dataset.description))
logging.info(' Output data set: %s' % (self.out_dataset.description))
if (self.progress_report == None):
logging.info(' No progress reported.')
else:
logging.info(' Progress report every: %d%%' % (self.progress_report))
logging.info(' Pass field list: %s' % (str(self.pass_field_list)))
logging.info(' Component standardisers:')
for cs in self.comp_stand_list:
logging.info(' Name: %s' % (str(cs[0].description)))
logging.info(' Input fields: %s' % (str(cs[0].in_fields)))
logging.info(' Input field indices: %s' % (str(cs[1])))
logging.info(' Output fields: %s' % (str(cs[0].out_fields)))
logging.info(' Output field indices: %s' % (str(cs[2])))
# ---------------------------------------------------------------------------
def standardise(self):
"""Standardise all records in the input data set and write them into the
output data set.
"""
num_output_fields = len(self.out_dataset.field_list)
# Calculate a counter for the progress report
#
if (self.progress_report != None):
progress_report_cnt = int(self.in_dataset.num_records / \
(100.0 / self.progress_report))
progress_report_cnt = max(1, progress_report_cnt) # Make it positive
else: # So no progress report is being logged
progress_report_cnt = in_dataset.num_records + 1
start_time = time.time()
rec_read = 0 # Number of records read from data set
# Loop over all records from input data set - - - - - - - - - - - - - - - -
#
for (rec_ident, in_rec) in self.in_dataset.readall():
out_rec = ['']*num_output_fields # Create output record with empty fields
# First copy pass fields from input to output record - - - - - - - - - -
#
for (in_field_ind, out_field_ind) in self.pass_field_index_list:
out_rec[out_field_ind] = in_rec[in_field_ind]
# Process one component standardiser after the other - - - - - - - - - -
#
for cs_details in self.comp_stand_list:
cs = cs_details[0]
in_field_index_list = cs_details[1]
out_field_index_list = cs_details[2]
num_input_fields = len(in_field_index_list)
# First get the input record field values
#
in_rec_val_list = []
for in_index in in_field_index_list:
if (in_index != None):
in_rec_val_list.append(in_rec[in_index])
# Check for word spilling if more than one field - - - - - - - - - - -
#
if ((cs.check_word_spill == True) and (num_input_fields > 1)):
in_str = '' # The input string for the component standardiser
for in_val in in_rec_val_list:
spill_flag = cs.check_field_spill(in_str, in_val)
if (spill_flag == True):
in_str = in_str + in_val
else: # Use given field separator
in_str = in_str + cs.field_sep + in_val
else:
in_str = cs.field_sep.join(in_rec_val_list)
# Clean the input string - - - - - - - - - - - - - - - - - - - - - - -
#
clean_in_str = cs.clean_component(in_str)
out_field_list = cs.standardise(in_str, clean_in_str)
assert len(out_field_list) == len(out_field_index_list), \
(clean_in_str, out_field_list)
i = 0
for out_index in out_field_index_list:
if (out_index != None):
out_rec[out_index] = out_field_list[i]
i += 1
# Write the standardised record into the output data set
#
self.out_dataset.write({rec_ident:out_rec})
rec_read += 1
if ((rec_read % progress_report_cnt) == 0): # Log progress - - - - - - -
used_time = time.time() - start_time
perc_done = 100.0 * rec_read / self.in_dataset.num_records
rec_time = used_time / rec_read # Time per record read and indexed
togo_time = (self.in_dataset.num_records - rec_read) * rec_time
used_sec_str = auxiliary.time_string(used_time)
rec_sec_str = auxiliary.time_string(rec_time)
togo_sec_str = auxiliary.time_string(togo_time)
log_str = 'Read and standardised %d of %d records (%d%%) in %s (%s' % \
(rec_read, self.in_dataset.num_records, round(perc_done),
used_sec_str, rec_sec_str) + \
' per record), estimated %s until finished.' % (togo_sec_str)
logging.info(log_str)
if (self.log_funct != None):
self.log_funct(log_str)
memory_usage_str = auxiliary.get_memory_usage()
if (memory_usage_str != None):
logging.info(' '+memory_usage_str)
# Finalise all component standardisers() - - - - - - - - - - - - - - - - -
#
for cs_details in self.comp_stand_list:
cs_details[0].finalise()
used_sec_str = auxiliary.time_string(time.time()-start_time)
rec_time_str = auxiliary.time_string((time.time()-start_time) / \
self.in_dataset.num_records)
logging.info('Read and standardised %d records in %s (%s per record)' % \
(self.in_dataset.num_records, used_sec_str, rec_time_str))
logging.info('')
# =============================================================================
class ComponentStandardiser:
"""Base class for component standardisers.
The following arguments must be given to the constructor of the base class
and all derived classes:
input_fields A list containing field names (that must be in the input
data set)
output_fields A list containing field names (that must be in the output
data set)
The following optional arguments can be used with all component
standardisers:
description A string describing the component standardiser.
field_separator A character that is used to join together field values
in a component before cleaning and standardisation is
done. Default values is the empty string ''.
check_word_spill A Flag, if set to true and a component is made of
several fields and the field_separator is set to a
whitespace character (' ') then the field spill method
will be called. Default is False.
tag_table Reference to a tag lookup table.
corr_list Reference to a correction list.
Note that for date and phone number standardisers the field separator
will automatically be set to the empty string '' and word spilling will
be set to False.
"""
# ---------------------------------------------------------------------------
def __init__(self, base_kwargs):
"""Constructor
"""
# General attributes for all component standardisers.
#
self.description = ''
self.in_fields = None # A string with a list of field names form the
# input data set, that will be standardised. The
# values in the fields will be concatenated into
# one string with the field separator string
# in between the values.
self.out_fields = None # A list of field names form the output data set
# into which the standardised component values
# will be stored.
self.corr_list = [] # A correction list for the cleaning step.
self.tag_table = {} # A lookup table containing tags and values with
# their corrections
self.field_sep = '' # Field separator character
self.check_word_spill = False # Flag for checking word spilling
self.alphanum = string.letters+string.digits # For word spill method
# Process base keyword arguments (all data set specific keywords were
# processed in the derived class constructor)
#
for (keyword, value) in base_kwargs.items():
if (keyword.startswith('desc')):
auxiliary.check_is_string('description', value)
self.description = value
elif (keyword.startswith('input_f')):
auxiliary.check_is_list('input_fields', value)
self.in_fields = value
elif (keyword.startswith('output_f')):
auxiliary.check_is_list('output_fields', value)
self.out_fields = value
elif (keyword.startswith('field_s')):
auxiliary.check_is_string('field_separator', value)
self.field_sep = value
elif (keyword.startswith('check_wo')):
auxiliary.check_is_flag('check_word_spill', value)
self.check_word_spill = value
elif (keyword.startswith('corr_l')):
auxiliary.check_is_list('corr_list', value)
self.corr_list = value
elif (keyword.startswith('tag_t')):
auxiliary.check_is_dictionary('tag_table', value)
self.tag_table = value
else:
logging.exception('Illegal constructor argument keyword: %s' % \
(str(keyword)))
raise Exception
# Check if fields are defined and not empty - - - - - - - - - - - - - - - -
#
auxiliary.check_is_list('input_fields', self.in_fields)
auxiliary.check_is_list('output_fields', self.out_fields)
if (len(self.in_fields) == 0) or (len(self.out_fields) == 0):
logging.exception('At least one of the field lists is empty.')
raise Exception
if (self.field_sep == ''): # No word spill checking with empty separator
self.check_word_spill = False
# ---------------------------------------------------------------------------
def clean_component(self, in_str):
"""Clean the given input string using a correction list.
This method cleans the input string by checking if any of the 'original'
strings given in the correction list is in the string. If so it will
replace such an original string with the corresponding replacement
string. It also strips off all leading and trailing spaces and makes all
letters lowercase. A cleaned string is returned.
"""
if (in_str.strip() == ''): # Check if the string only contains whitespaces
return ''
tmp_str = in_str.replace('\t',' ') # Replace tabs with whitespaces
# Make all lowercase and add leading and trailing whitespaces - - - - - -
# (this is to make sure replacement strings do match at beginning and end)
#
tmp_str = ' '+tmp_str.lower()+' '
for (org, repl) in self.corr_list: # Check for strings in correction list
if (org in tmp_str):
tmp_str = tmp_str.replace(org, repl)
# Make sure commas are separated from words so they become list elements -
#
tmp_str = tmp_str.replace(',', ' , ')
while (' ' in tmp_str): # Make sure there are no repeated spaces
tmp_str = tmp_str.replace(' ', ' ')
out_str = tmp_str.strip()
return out_str
# --------------------------------------------------------------------------
def check_field_spill(self, str1, str2):
"""Method to check if a known word is spilling from one string into
another.
Uses the keys the tag look-up table to check for known words.
Return 'True' if a word spills over, otherwise 'False'
"""
org_str1 = str1 # Keep copies of the original input string
org_str2 = str2
if ((str1 == '') or (str2 == '')): # One string is empty
return False
# Check if the characters at the 'boundary' are either letters or digits
#
if (str1[-1] in self.alphanum) and (str2[0] in self.alphanum):
min_ind = -len(str1)
ind =-1 # Start with last character
while (str1[ind] in self.alphanum) and (ind > min_ind):
ind -= 1
test_str1 = str1[ind:] # Only keep last word in string 1
max_ind = len(str2)
ind =0 # Start with first character
while (str1[ind] in self.alphanum) and (ind < max_ind):
ind += 1
test_str2 = str2[:ind] # Only keep first word in string 2
# Concatenate into one word and make a tuple so it conforms to tag table
# keys
#
check_tuple = (test_str1.lower() + test_str2.lower(),)
if (check_tuple in self.tag_table): # Found a word spilling
logging.info(' Found word spilling: "%s","%s" -> "%s"' % \
(org_str1, org_str2, check_word))
return True
else:
return False
# ---------------------------------------------------------------------------
def standardise(self, in_str, clean_in_str):
"""Standardise the given input string.
Will return a list with the standardised fields corresponding to the
list of output fields defined in the component standardiser.
See implementations in derived classes for details.
"""
logging.exception('Override abstract method in derived class')
raise Exception
# ---------------------------------------------------------------------------
def __tag_component__(self, in_str):
"""Tag an input component string using the tag look-up table and make it a
list.
This method cleans the input string and extracts words, numbers and
separators into a list. Each element of this list is assigned one or
more tags. A 'greedy tagger' is applied, which cheques sequences of list
elements in the given lookup table (longer sequences first) and replaces
them with the string and tag from the lookup table if found.
Returns two lists:
token_list Contains the tokens (words, numbers, etc.) from the input
string separated at whitespace characters.
tag_list One or more tags for each of the tokens in the token list.
"""
# First, split input string into elements at spaces - - - - - - - - - - - -
#
org_list = in_str.split() # The original list from the input string
token_list = [] # The initially empty list of tokens
tag_list = [] # The initially empty list of tags
max_key_len = self.tag_table.max_key_length
while (org_list != []): # As long as not all elements have been processed
tmp_list = org_list[:max_key_len]
# Extract longest sub-list
tmp_val = [] # Start with empty value
tmp_key = tuple(tmp_list)
while (tmp_key != ()): # As long as key not empty and not found in lookup
if (self.tag_table.has_key(tmp_key)):
tmp_val = self.tag_table[tmp_key]
break
tmp_key = tmp_key[:-1] # Remove last element in key
if (tmp_val != []): # A value has been found in the dictionary - - - - -
tmp_len = len(tmp_key) # Length of found sequence
if (tmp_val[0] != ''): # It's not an empty value
token_list.append(tmp_val[0]) # Append corrected word (or sequence)
tag_list.append(tmp_val[1]) # Append tag or tags
else: # No value has been found in the lookup dictionary, try other tags
tmp_val = org_list[0] # Value is first element in the original list
tmp_len = 1
if (len(tmp_val) == 1) and (tmp_val.isalpha()): # A 1-letter word - -
token_list.append(tmp_val)
tag_list.append('II')
elif (tmp_val.isdigit()): # Element is a number - - - - - - - - - - -
token_list.append(tmp_val)
if (len(tmp_val) == 4):
tag_list.append('N4')
else:
tag_list.append('NU')
elif (not tmp_val.isalpha()) and tmp_val.isalnum(): # Alpha-numeric -
token_list.append(tmp_val)
tag_list.append('AN')
elif (tmp_val == '-'): # Element is a hyphen - - - - - - - - - - - - -
# Only append if previous element is not a hyphen, vertical bar, or
# brackets
#
if ((token_list == []) or \
(tag_list[-1] not in ['HY','VB','OB','CB'])):
token_list.append(tmp_val)
tag_list.append('HY')
elif (tmp_val == ','): # Element is a comma - - - - - - - - - - - - -
pass # Don't append
elif (tmp_val == '|'): # Element is a vertical bar - - - - - - - - - -
# Remove a pair of vertical bars
#
if ((token_list != []) and (tag_list[-1] == 'VB')):
tag_list = tag_list[:-1]
token_list = token_list[:-1]
# Replace previous hyphen a vertical bar
#
elif ((token_list != []) and (tag_list[-1] == 'HY')):
token_list[-1] = tmp_val
tag_list[-1] = 'VB'
else: # Simple append vertical bar
token_list.append(tmp_val)
tag_list.append('VB')
elif (tmp_val == '('): # Element is an opening bracket - - - - - - - -
# Replace previous hyphen with an opening bracket
#
if ((token_list != []) and (tag_list[-1] == 'HY')):
token_list[-1] = tmp_val
tag_list[-1] = 'OB'
# Only append if previous element is not an opening bracket
#
elif ((token_list == []) or (tag_list[-1] != 'OB')):
token_list.append(tmp_val)
tag_list.append('OB')
elif (tmp_val == ')'): # Element is an closing bracket - - - - - - - -
# Remove a pair of opening / closing brackets
#
if ((token_list != []) and (tag_list[-1] == 'OB')):
tag_list = tag_list[:-1]
token_list = token_list[:-1]
# Replace previous hyphen with a closing bracket
#
elif ((token_list != []) and (tag_list[-1] == 'HY')):
token_list[-1] = tmp_val
tag_list[-1] = 'CB'
# Only append if previous element is not a closing bracket
#
elif ((token_list == []) or (tag_list[-1] != 'CB')):
token_list.append(tmp_val)
tag_list.append('CB')
else: # An unknown element - - - - - - - - - - - - - - - - - - - - - -
token_list.append(tmp_val)
tag_list.append('UN')
# Finally remove the processed elements from the original element list
#
org_list = org_list[tmp_len:] # Remove processed elements
# Remove certain elements from start and end - - - - - - - - - - - - - - -
#
while ((len(tag_list) > 1) and (tag_list[0] in ['CO','HY','SP'])):
tag_list = tag_list[1:]
token_list = token_list[1:]
while ((len(tag_list) > 1) and (tag_list[-1] in ['CO','HY','SP'])):
tag_list = tag_list[:-1]
token_list = token_list[:-1]
# Remove vertical bars or brackets from start and end - - - - - - - - - - -
#
while ((len(tag_list) > 2) and \
((tag_list[0] == 'VB') and (tag_list[-1] == 'VB')) or \
((tag_list[0] == 'OB') and (tag_list[-1] == 'CB'))):
tag_list = tag_list[1:-1]
token_list = token_list[1:-1]
return [token_list, tag_list]
# ---------------------------------------------------------------------------
def __write_hmm_train_record__(self, in_str, tok_list, tag_perm_list,
state_list, hmm_prob):
"""Write the given record, the list of its tag sequence permutations, and
possibly its HMM state sequence into the training file.
If the sequence frequency file is given also insert the sequences with
their probabilities and input strings into the sequence frequency
dictionary.
"""
self.hmm_train_fp.write('# Input string: %s' % (in_str)+os.linesep)
self.hmm_train_fp.write('# Token list: %s' % (tok_list)+os.linesep)
list_len = len(tok_list)
if (state_list == None): # Create an empty state sequenct list
state_list = [' ']*list_len
for tag_list in tag_perm_list:
assert len(tag_list) == len(tok_list)
tag_state_list = []
for i in range(list_len):
tag_state_list.append(tag_list[i]+':'+state_list[i])
tag_state_str = ', '.join(tag_state_list)
self.hmm_train_fp.write('%s' % (tag_state_str)+os.linesep)
# Add sequence into sequence probability dictionary if defined - - - - -
#
if (self.hmm_seq_prob_file != None):
seq_list = self.hmm_seq_prob_dict.get(tag_state_str, [])
seq_list.append((in_str, hmm_prob))
self.hmm_seq_prob_dict[tag_state_str] = seq_list
self.hmm_train_fp.write(os.linesep)
# ---------------------------------------------------------------------------
def __write_hmm_seq_prob_file__(self, hmm_name_str):
"""Write the dictionary with sequence frequencies into file.
Sort according to frequency (count of occurrence) of a sequence, with
high frequencies first (as these are the ones one wants to get correct).
"""
try:
self.hmm_seq_prob_fp = open(self.hmm_seq_prob_file, 'w')
except:
logging.exception('Cannot write to HMM sequence probability file: ' + \
'"%s"' % (self.hmm_seq_prob_file))
self.hmm_seq_prob_fp.write('#'+'#'*70 + os.linesep) # Write a header
self.hmm_seq_prob_fp.write('# HMM sequence probabilities for: "%s"' % \
(hmm_name_str)+ os.linesep)
self.hmm_seq_prob_fp.write('#' + os.linesep)
self.hmm_seq_prob_fp.write('# Created '+time.ctime(time.time()) + \
os.linesep)
self.hmm_seq_prob_fp.write('#' + os.linesep)
sorted_seq_key_list = [] # Make a list for easy sorting
num_rec = 0 # Count total number of records
for (tag_state_str, seq_list) in self.hmm_seq_prob_dict.iteritems():
hmm_prob = self.hmm_seq_prob_dict[tag_state_str][0][1]
sorted_seq_key_list.append((len(seq_list), hmm_prob, tag_state_str))
num_rec += len(seq_list)
sorted_seq_key_list.sort(reverse=True)
cum_freq = 0 # Cumulative frequency seen so far
for (freq, hmm_prob, tag_state_str) in sorted_seq_key_list:
self.hmm_seq_prob_fp.write('# Pattern: %s' % (tag_state_str) + \
os.linesep)
cum_freq += freq
freq_perc = 100.0*freq / float(num_rec)
cum_freq_perc = 100.0*cum_freq / float(num_rec)
self.hmm_seq_prob_fp.write('# Frequency: %d (%.2f%%, cumulative:' % \
(freq, freq_perc) + ' %.2f%%)' % \
(cum_freq_perc) + os.linesep)
examples = self.hmm_seq_prob_dict[tag_state_str]
self.hmm_seq_prob_fp.write('# Normalised HMM Viterbi probability: ' + \
'%.20f' % (hmm_prob) + os.linesep)
self.hmm_seq_prob_fp.write('# Example input strings:' + os.linesep)
for (example_str, prob) in examples[:10]: # Only 10 first examples
self.hmm_seq_prob_fp.write('# %s' % (example_str) + os.linesep)
self.hmm_seq_prob_fp.write('%s' % (tag_state_str) + os.linesep)
self.hmm_seq_prob_fp.write(os.linesep)
self.hmm_seq_prob_fp.write('# End.' + os.linesep)
self.hmm_seq_prob_fp.close()
# ---------------------------------------------------------------------------
def finalise(self):
"""Method to do any final work, such as writing information to files.
"""
return # Nothing to do for general case.
# ---------------------------------------------------------------------------
def log(self, instance_var_list = None):
"""Write a log message with the basic component standardiser instance
variables plus the instance variable provided in the given input list
(assumed to contain pairs of names (strings) and values).
"""
logging.info('')
logging.info('Component standardiser: "%s"' % (self.description))
logging.info(' Input fields: %s' % (str(self.in_fields)))
logging.info(' Output fields: %s' % (str(self.out_fields)))
logging.info(' Field separator: "%s"' % (self.field_sep))
logging.info(' Check word spilling: %s' % (str(self.check_word_spill)))
if (self.corr_list != []):
logging.info(' Length of correction list: %d' % (len(self.corr_list)))
if (self.tag_table != {}):
logging.info(' Length of tag lookup table: %d' % (len(self.tag_table)))
if (instance_var_list != None):
logging.info(' Standardiser specific variables:')
max_name_len = 0
for (name, value) in instance_var_list:
max_name_len = max(max_name_len, len(name))
for (name, value) in instance_var_list:
pad_spaces = (max_name_len-len(name))*' '
logging.info(' %s %s' % (name+':'+pad_spaces, str(value)))
# =============================================================================
class DateStandardiser(ComponentStandardiser):
"""Class for standardising dates into three field: day, month, year.
The 'output_fields' must be a list of three fields, the first field is for
day, the second for month and the third for year. Fields can be set to
'None' if no output is to be written, as long as at least one field is
set. For example, if one is only interested in the year, then the output
fields can be set to: output_fields = [None, None, "year_field"].
Note that field spill checking is not possible for this standardiser.
The additional arguments (besides the base class arguments) that need to
be set when this standardiser is initialised are:
parse_formats A list containing one or several strings with a date
parsing format. The parsing formats must each contain
three of the following format strings with a space in
between (e.g. '%d %m %Y'):
%b Abbreviated month name (Jan, Feb, Mar, etc.)
%B Full month name (January, February, etc.)
%d Day of the month as a decimal number [01,31]
%m Month as a decimal number [01,12]
%y Year without century as a decimal number [00,99]
%Y Year with century as a decimal number
The parsing routine tries one format after the other and
as soon as a format is successful returns the
corresponding parsed date. Date formats more commonly
used should therefore be at the top of the parse format
list.
Besides the spaces between the three parsing directives,
format strings must not contain any other characters,
such as '\/:-' etc. as they will be removed from the
input values before date parsing is attempted.
pivot_year Value of pivot year (between 00 and 99) that controls
expansion of two-digit year values into four-digit year
values. Two-digits years smaller than the pivot year will
be expanded into 20XX, years larger and equal than the
pivot year will be expanded into 19xx
For example: pivot_year = 03: 68 -> 1968
03 -> 1903
02 -> 2002