Source

Kiva Editor's Assistant / rules.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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Classes derived from Rule.
"""
import re
import sys
import logging
import inspect
import pycountry
import unicodedata
from abc import ABCMeta, abstractmethod

from mytoken import Token
from tokensearch import TokenSearchByRegexp


class Rule():
    """Abstract base class for rules.
    """

    # for Python 3 use class Rule(metaclass=ABCMeta):
    __metaclass__ = ABCMeta

    def __init__(self, rule_id, description, enabled=True):
        """Initialize descriptive parameters.

        Arguments:
        - `rule_id`: a globally unique integer.

        - `description`: a human-readable explanation of what this
          rule does.

        - `enabled`: for efficiency, rules can opt out of the main
          loop by setting this attribute to False. Rules should
          tolerate being re-enabled at any time, and apply()
          should function correctly regardless of this value.
        """
        self.rule_id = rule_id
        self.description = description
        self.enabled = enabled

    def __str__(self):
        return self.__class__.__name__

    @abstractmethod
    def apply(self, ea):
        """Apply this rule to the tokens in EditAssistant object `ea`.
        """
        pass

INITIAL_PHASE = 0
POS_PHASE     = 1
PARSED_PHASE  = 2

PHASE_NAME = ['Initial', 'Part-of-Speech Tagged', 'Parsed']


def get_rules(desired_phase):
    """Return a list containing instances of all the rules in this
    module with a matching phase, sorted by rule id."""
    classes = []
    this_module = sys.modules[__name__]
    for name, obj in inspect.getmembers(this_module, inspect.isclass):
        if (obj.__module__ == this_module.__name__ and
            'Rule' in str(obj) and
            getattr(obj, 'phase', None) == desired_phase):
            classes.append(obj())
    # sort by id
    return sorted(classes, cmp=lambda x, y: cmp(x.rule_id, y.rule_id))


def get_neighbor(lst, i, step, attrib_name=None):
    assert(step != 0)
    neighbor = None
    j = i + step
    while 0 <= j < len(lst):
        if not attrib_name:
            neighbor = lst[j]
            break
        try:
            val = getattr(lst[j], attrib_name)
            if val:
                neighbor = lst[j]
                break
        except:
            pass
        j += step
    return neighbor


def get_left_neighbor(lst, i, attrib_name=None):
    return get_neighbor(lst, i, -1, attrib_name)


def get_right_neighbor(lst, i, attrib_name=None):
    return get_neighbor(lst, i, 1, attrib_name)


def get_neighbors(lst, i, attrib_name=None):
    """Return a tuple of the elements before and after lst[i].

    If `attrib_name` is specified, return the closest elements having an
    attribute of that name that evaluates to true.
    """
    return (get_left_neighbor(lst, i, attrib_name),
            get_right_neighbor(lst, i, attrib_name))


def split_token_at_delim(caller, tokens, transform_token_index, delim,
                         keep_delim):
    """
    Split the token at tokens[transform_token_index] into multiple
    tokens delimited by `delim`.

    Arguments:
    caller -- name of calling function to print in debug logging

    tokens -- array of Token objects; new Tokens will be inserted if
    delimiter character is found.

    transform_token_index -- 0-based index into `tokens`

    delim -- delimiter character

    keep_delim -- if set, transform runs of delimiter characters into
    Tokens, otherwise discard them when splitting.

    If the token to split consists of nothing but delimiter characters,
    then it is either left unchanged if `keep_delim` is set or it is
    deleted if `keep_delim` is not set.
    """
    token_to_transform = tokens[transform_token_index]
    split_tokens = []
    # accumulate non-delimiter characters in split_str
    split_str = u''
    # if keep_delim is set, then accumulate runs of delimiter characters
    # in delim_token.
    delim_token = None
    for i, c in enumerate(token_to_transform.str):
        if c == delim:
            # if delimiter has just occurred after one or more
            # non-delimiter characters, add those characters as a new
            # token.
            if split_str:
                cbegin = token_to_transform.cbegin + i - len(split_str)
                cend = cbegin + len(split_str)
                split_tokens.append(Token(split_str, cbegin, cend))
                split_str = u''
            # if we're keeping delimiter characters, accumulate this one
            if keep_delim:
                if not delim_token:
                    cbegin = token_to_transform.cbegin + i
                    delim_token = Token(delim, cbegin, cbegin + 1)
                else:
                    delim_token.str = delim_token.str + delim
                    delim_token.cend += 1
        else:
            if delim_token:
                split_tokens.append(delim_token)
                delim_token = None
            split_str += c
    # it shouldn't be possible to have both a split_str and a
    # delim_token to append to the split_tokens list because whenever
    # one is encountered the other is emptied.
    assert(not (split_str and delim_token))
    if split_str:
        cbegin = token_to_transform.cbegin + i + 1 - len(split_str)
        cend = cbegin + len(split_str)
        split_tokens.append(Token(split_str, cbegin, cend))
    if delim_token:
        split_tokens.append(delim_token)
    if len(split_tokens) > 1:
        # insert all but the last of split_tokens before the token at
        # transform_token_index, then make the token at
        # transform_token_index look like the last token in split_tokens.
        for i, token_to_insert in enumerate(split_tokens[:-1]):
            logging.debug(u'stad {} inserting {} before {}'.format(
                    caller, token_to_insert,
                    tokens[transform_token_index + i]))
            tokens.insert(transform_token_index + i, token_to_insert)
        transform_token_index += i + 1
        logging.debug(u'stad {} changing {} to {}'.format(
                caller, tokens[transform_token_index],
                split_tokens[-1]))
        tokens[transform_token_index].str = split_tokens[-1].str
        tokens[transform_token_index].cbegin = split_tokens[-1].cbegin
        tokens[transform_token_index].cend = split_tokens[-1].cend
        return True
    return False

def split_token_at_index(caller, tokens, transform_token_index, split_index,
                         three_way):
    token_to_transform = tokens[transform_token_index]
    if (three_way and
        split_index < len(token_to_transform.str) - 1):
        left = token_to_transform.str[:split_index]
        middle = token_to_transform.str[split_index]
        right = token_to_transform.str[split_index + 1:]

        cbegin = token_to_transform.cbegin
        cend = cbegin + len(left)
        new_token = Token(left, cbegin, cend)
        logging.debug('{} inserting {} before {}'.format(
                caller, new_token,
                tokens[transform_token_index]))
        tokens.insert(transform_token_index, new_token)
        cbegin = cend
        cend = cbegin + len(middle)
        original = str(token_to_transform)
        token_to_transform.str = middle
        token_to_transform.cbegin = cbegin
        token_to_transform.cend = cend
        logging.debug('{} changing {} to {}'.format(
                caller, original,
                token_to_transform))

        cbegin = cend
        cend = cbegin + len(right)
        new_token = Token(right, cbegin, cend)
        logging.debug('{} inserting {} before {}'.format(
                caller, new_token,
                tokens[transform_token_index + 2]))
        tokens.insert(transform_token_index + 2, new_token)
    else:
        # split the token string at the supplied character index
        index = split_index
        if index == 0 and index < len(token_to_transform.str) - 1:
            index += 1
        left = token_to_transform.str[:index]
        right = token_to_transform.str[index:]
        # insert a new token for the left part of the split
        cbegin = token_to_transform.cbegin
        if cbegin != None:
            cend = cbegin + len(left)
        else:
            cend = None
        new_token = Token(left, cbegin, cend)
        logging.debug('{} inserting {} before {}'.format(caller, new_token,
            tokens[transform_token_index]))
        tokens.insert(transform_token_index, new_token)
        original = str(token_to_transform)
        token_to_transform.str = right
        token_to_transform.cbegin = cend
        if cend != None:
            token_to_transform.cend = cend + len(right)
        else:
            token_to_transform.cend = None
        logging.debug('{} changed {} to {}'.format(caller, original,
                                                   token_to_transform))


# ---------------------------------------------------------------------------
#
# Initial Phase rules.
#
# ---------------------------------------------------------------------------

class WhitespaceSplitRule(Rule):
    phase = INITIAL_PHASE

    def __init__(self):
        Rule.__init__(self, 5, "Separate text by whitespace.")

    def apply(self, ea):
        changed = False
        for i, token in enumerate(ea.tokens):
            if token.is_para or token.non_printing:
                continue
            if ' ' in token.str:
                split_token_at_delim(self, ea.tokens, i, ' ', False)
                changed = True
        return changed


class RegexCleanupRule(Rule):
    """Generate transforms for tokens matching any of a variety of
    regular expressions used to clean up common errors.

    This rule works best when run before the original text is split.
    """

    phase = INITIAL_PHASE
    regex_pairs = [
        # Character standardization
        TokenSearchByRegexp(u'“|”', u'"'),
        TokenSearchByRegexp(u"’", u"'"),

        # misspellings
        TokenSearchByRegexp(u'dependants', u'dependents'),
        TokenSearchByRegexp(ur'therefor', u'therefore'),
        TokenSearchByRegexp(ur'(?i)(micro) finance', u'\1finance'),

        # proper nouns
        TokenSearchByRegexp(u'congo town', u'Congo Town'),
        TokenSearchByRegexp(u'lake victoria', u'Lake Victoria'),
        TokenSearchByRegexp(u'Pre-angkorean', u'pre-Angkorean'),
        TokenSearchByRegexp(u'KIVA', u'Kiva'),
        TokenSearchByRegexp(u'KADET LTD', u'KADET Ltd.'),

        # awkward or verbose constructions
        TokenSearchByRegexp(u'requested for', u'requested'),
        TokenSearchByRegexp(u'has given birth to', 'has'),
        TokenSearchByRegexp(u'requesting to borrow', u'asking to borrow'),
        TokenSearchByRegexp(u'adult-aged', u'adult'),
        TokenSearchByRegexp(ur'and etc\.*', u'etc.'),
        TokenSearchByRegexp(u'infant-aged', u'infant'),
        TokenSearchByRegexp(u'requesting for a', u'requesting a'),
        TokenSearchByRegexp(u'requested a loan for ([0-9]+)',
                            ur'requested a loan of \1'),
        TokenSearchByRegexp(ur'he is widowed', u'he is a widower'),
        TokenSearchByRegexp(u'borrowed a loan', u'took out a loan'),
        TokenSearchByRegexp(u'in a business of', u'in the business of'),
        TokenSearchByRegexp(
            u'with (.+) children and (.+) of them go to school',
            ur'and has \1 children, \2 of whom go to school'),
        TokenSearchByRegexp(u'to invest in expanding the business',
                            u'to expand the business'),
        TokenSearchByRegexp(u'fisherfolks', u'fishermen'),
        TokenSearchByRegexp(u'aspired for', u'wanted'),
        TokenSearchByRegexp(u"uplifting the family's standard",
                            u"raising the family's standard"),
        TokenSearchByRegexp(u'could continue to save up',
                            u'can continue to save'),
        TokenSearchByRegexp(u'from the Word of God she received',
                            u'from the Word of God she studies'),
        TokenSearchByRegexp(u'raise & sell in future', u'raise and sell'),
        TokenSearchByRegexp(u'married with ([0-9]+) (child|children)',
         ur'married and has \1 \2'),
        TokenSearchByRegexp(u'has a long experience',
                            u'has a lot of experience'),
        TokenSearchByRegexp(u'is aiming to gain more profits',
                            u'aims to make more money'),
        TokenSearchByRegexp(u'has a good experience in this field and a good '
         'reputation and (s?he) is being well known in (his|her) area',
         ur' has a lot of experience in this field, a good reputation, '
         ur'and is well known in \2 area'),

        # Chiefly British
        TokenSearchByRegexp(u'([iI]n) future', ur'\1 the future'),
        TokenSearchByRegexp(u'tyres', u'tires'),
        TokenSearchByRegexp(u'neighbour', u'neighbor'),
        TokenSearchByRegexp(u'licencing', u'licensing'),

        # non-ISO currency abbreviations
        TokenSearchByRegexp(ur'(.+)/=', ur'\1 UGX'),
        TokenSearchByRegexp(ur'(?i)ksh(?:s|)(?:\.|)([0-9,.]+|)', ur'KES \1'),
        TokenSearchByRegexp(ur'[Pp]hp', 'PHP'),
        TokenSearchByRegexp(ur'P([0-9,.]+)', ur'\1 PHP'),
        TokenSearchByRegexp(ur'(?i)LE ([0-9]*)', ur'SLL \1'),
        TokenSearchByRegexp(ur'Rp\.', 'IDR'),

        # incorrect punctuation
        TokenSearchByRegexp(ur'e\.t\.c\.?', u'etc.'),
        TokenSearchByRegexp(ur'\betc([^.])', ur'etc.\1'),
        TokenSearchByRegexp(ur'(?<!\.)\.\.(?!\.)', u'.'),  # blah.. -> blah.

        # grammatical errors
        TokenSearchByRegexp(ur'1 infant-aged children', u'one infant child'),
        TokenSearchByRegexp(ur'1 years', u'one year'),
        TokenSearchByRegexp(ur'never missed any meeting\.',
                            u'never missed any meetings.'),

        # Field partner template cleanup
        # TokenSearchByRegexp(ur'To make a living,'
        #    '(?P<name>(\w|\s)+) owns & operates a business'
        #    'venture in the [a-z]+ sector \w+ (?P<business>[^.]+\.)',
        #  ur'\g<name> has a \g<business>'),
        TokenSearchByRegexp(
            u'[Ww]hile not the only means for generating revenue, the',
            u'The'),
        TokenSearchByRegexp(
            u'main source of income for the business comes primarily from',
            u'main source of income for the business comes from'),
        TokenSearchByRegexp(u'a month for these activities',
                            u'a month from it'),
        TokenSearchByRegexp(u'comes from buying and selling of',
                            u'comes from selling'),
        TokenSearchByRegexp(u'engage in business activities', u'do business'),
        # TODO: really want "improve / expand" NP "business"
        # TokenSearchByRegexp(
        #     u"improve / expand the borrower's business",
        #     u'improve and expand it'),
        TokenSearchByRegexp(ur'fellowship\* meeting', u'fellowship meeting*'),
        TokenSearchByRegexp(u'clicking the link to the NWTF Kiva lending team',
         ur'clicking the link to the '
         '<a href="http://www.kiva.org/team/nwtf_philippines">'
         'NWTF Kiva lending team</a>'),
        TokenSearchByRegexp(
            u'Kiva\'s Muslim World Lending helptext: '
            u'http://tinyurl.com/3aekx8m',
            u'Kiva\'s article on <a href="http://na3.salesforce.com/_ui/'
            'selfservice/pkb/'
            'PublicKnowledgeSolution/d?orgId=00D500000006svl&lang=1&id=501'
            '50000000SN1N&retURL=/sol/public/solutionbrowser.jsp%3Fsearch%3D'
            'muslim%2Bworld%26cid%3D02n50000000DUOS%26orgId%3D00D500000006svl'
            '%26lang%3D1%26t%3D4&ps=1&pPv=1">Lending in the Muslim World</a>'),

        # Jargon
        TokenSearchByRegexp(u'cycle loan', u'loan'),
        TokenSearchByRegexp(u'loan cycle', u'loan'),
        TokenSearchByRegexp(u'loan facility', u'loan'),

        # Numeric expressions
        TokenSearchByRegexp(ur'1st', u'first'),
        TokenSearchByRegexp(ur'2nd', u'second'),
        TokenSearchByRegexp(ur'3rd', u'third'),
        TokenSearchByRegexp(ur'4th', u'fourth'),
        TokenSearchByRegexp(ur'5th', u'fifth'),
        TokenSearchByRegexp(ur'6th', u'sixth'),
        TokenSearchByRegexp(ur'7th', u'seventh'),
        TokenSearchByRegexp(ur'8th', u'eighth'),
        TokenSearchByRegexp(ur'9th', u'ninth'),

        ]

    def __init__(self):
        Rule.__init__(self, 10, "Search and replace specific strings")

    def apply(self, ea):
        changed = False
        for ts in RegexCleanupRule.regex_pairs:
            if ts.apply(self, ea.tokens):
                changed = True
        return changed


class ParagraphRule(Rule):
    """Divide a single token containing embedded newlines into
    multiple tokens.
    """

    phase = INITIAL_PHASE
    LINEBREAK_RE = re.compile(r'(\s*)(\n+)(\s*)')

    def __init__(self):
        Rule.__init__(self, 20,
                      "Separate text into paragraphs at line breaks.")

    def apply(self, ea):
        changed = False
        # search for a newline, consider it and all contiguous remaining
        # whitespace (including other newlines) to be a single paragraph break.
        for transform_token_index, token in enumerate(ea.tokens):
            if token.is_para or token.non_printing:
                continue
            mo = ParagraphRule.LINEBREAK_RE.search(token.str)
            if not mo:
                continue

            # Found a linebreak. Break the token at the linebreak into
            # two halves, inserting a paragraph token between them. Note
            # there might be other paragraph breaks beyond the first
            # one. They will be addressed when the main loop applies
            # this rule again.

            left_str = token.str[:mo.start()]
            right_str = token.str[mo.end():]
            left_token = None
            right_token = None

            if left_str:
                if right_str:
                    # token.str has the form left_str + '\n' +
                    # right_str, where left_str is some non-empty string
                    # that doesn't contain a newline and right_str is
                    # some non-empty string.
                    left_cend = token.cbegin + len(left_str)
                    left_token = Token(left_str, token.cbegin, left_cend)
                    right_cbegin = token.cbegin + mo.end()
                    right_token = Token(right_str, right_cbegin,
                                        right_cbegin + len(right_str))
                else:
                    # token == left_str + '\n'
                    left_token = Token(left_str, token.cbegin,
                                       token.cbegin + len(left_str))
                paragraph_token = Token(u'\n', left_token.cend,
                                        left_token.cend + 1)
            else:
                if right_str:
                    # token == '\n' + right_str
                    right_token = Token(right_str, token.cbegin + 1,
                                        token.cbegin + 1 + len(right_str))
                else:
                    # token == two or more '\n'
                    pass
                paragraph_token = Token(u'\n', token.cbegin, token.cbegin + 1)

            # replace the token we're transforming
            ea.tokens[transform_token_index] = paragraph_token
            changed = True
            # insert a token to its left if it is nonempty
            if left_token:
                ea.tokens.insert(transform_token_index, left_token)
                # that insertion has made transform_token_index off by
                # one; correct it.
                transform_token_index += 1
            # now insert the token to the right, if it is nonempty
            if right_token:
                ea.tokens.insert(transform_token_index + 1, right_token)
            logging.debug(u'ParagraphRule: %s',
                          filter(None,
                                 [left_token, paragraph_token, right_token]))
        return changed


class DotSplitRule(Rule):
    """Split tokens containing dots, unless the tokens are abbreviations
    or URLs.

    Split a word with a period to enforce spaces after punctuation, and
    for the benefit of other rules like spell checker and part of speech
    tagger.

    So "One sentence.And another." should become the tokens:
    One sentence . and another .
    Do not split if it is:
    - a URL, e.g. example.com should remain intact
    - a european style number like 1.000,00 (a separate rule
      will convert this to american style)
    - a decimal like 1.5 or .5 (latter should be changed to 0.5)
    - an abbreviation
    """

    phase = INITIAL_PHASE

    def __init__(self):
        Rule.__init__(self, 40,
                      "Separate periods from words that aren't abbreviations.")

    def _transform_abbrev(self, tokens, transform_token_index, abbrev,
                          abbrev_len):
        changed = False
        token_to_transform = tokens[transform_token_index]
        token_to_transform.abbrev = True

        # If the abbreviation matches the entire token, it does not need
        # to be split into multiple tokens, so update it in place.
        if abbrev_len == len(token_to_transform.str):
            if abbrev.normal_form:
                original = str(token_to_transform)
                token_to_transform.str = abbrev.normal_form
                logging.debug('DotSplitRule changing {} to {}'.format(
                        original, token_to_transform))
                changed = True
            return changed

        # The abbreviation matches just the start of the token. Make a
        # new token to insert after the abbreviation.
        if abbrev.normal_form:
            abbrev_part = abbrev.normal_form
        else:
            abbrev_part = token_to_transform.str[:abbrev_len]
        extra_part = token_to_transform.str[abbrev_len:]

        # Now modify the existing token, and create a new one to insert
        # after it.
        original = str(token_to_transform)
        token_to_transform.str = abbrev_part
        token_to_transform.cend = (token_to_transform.cbegin +
                                   len(abbrev_part))
        post_abbrev_token = Token(extra_part, token_to_transform.cend,
                                  token_to_transform.cend + len(extra_part))
        logging.debug('DotSplitRule changing {} to {}, {}'.format(
                original, token_to_transform, post_abbrev_token))
        tokens.insert(transform_token_index + 1, post_abbrev_token)
        return True

    def apply(self, ea):
        changed = False
        for i, token in enumerate(ea.tokens):
            if token.non_printing or not '.' in token.str:
                continue
            # Token has a dot in it somewhere. Leave it alone if it's
            # supposed to have embedded dots and is not an abbreviation.
            if token.is_URL or token.has_digits:
                continue

            # check if the token is or starts with an abbreviation
            abbrev_len, abbrev = token.abbrev_match_len

            if abbrev_len:
                if token.is_abbrev:
                    # token is an abbreviation
                    if abbrev.normal_form and token.str != abbrev.normal_form:
                        # but it differs from the proper form of the
                        # abbrev
                        original = str(token)
                        token.str = abbrev.normal_form
                        logging.debug('DotSplitRule changing {} to {}'.format(
                                original, token))
                        changed = True
                elif self._transform_abbrev(ea.tokens, i, abbrev, abbrev_len):
                    # token starts with an abbreviation was split
                    changed = True
            else:
                changed = split_token_at_delim(self, ea.tokens, i, u'.', True)
        return changed


class EuroDelimiterRule(Rule):
    """Convert European style delimited numbers to American style.

    For example, 1.234.567 becomes 1,234,567
    """

    phase = INITIAL_PHASE

    euro_decimal_number_re = re.compile(
        """# up to three digits, but no leading zeros
           [1-9]\d{0,2}
           # followed by one or more period-delimited three-digit groups
           (\.\d\d\d)+
           # with an optional comma-delimited decimal
           (,\d\d)?
        """, re.I | re.U | re.VERBOSE)

    def __init__(self):
        Rule.__init__(
            self, 50, "Convert European style thousands"
            " delimiters '1.234.567,89' to American style '1,234,567.89'.")

    def apply(self, ea):
        changed = False
        for token in ea.tokens:
            if token.non_printing or token.is_URL:
                continue
            mo = EuroDelimiterRule.euro_decimal_number_re.match(token.str)
            if mo:
                replacement = token.str.replace(u',', u'x')
                replacement = replacement.replace(u'.', u',')
                replacement = replacement.replace(u'x', u'.')
                logging.debug(u'EuroDelimiterRule changing {} to {}'.format(
                        token.str, replacement))
                token.str = replacement
                changed = True
        return changed


class PunctSplitRule(Rule):
    """Split punctuation (other than periods) into separate tokens.

    Avoid splitting numeric punctuation, e.g., 11,000.34 should not be
    split at the comma or the decimal. Also avoid splitting at
    apostrophes in contractions.

    Do not split at single hyphens, because the parser fails at
    expressions like "47" "year" "-" "old" but succeeds when given a
    token sequence like "47" "year-old" (the tagger labels "year-old" as
    JJ).

    Do not split asterisk from start of word.
    """

    phase = INITIAL_PHASE

    # this is the same as Token.delimited_decimal_re except that
    # it is not bookended by ^ and $
    embedded_decimal_number_re = re.compile(
        ur"""(-|\+)?      # negative or positive sign
             [0-9]{1,3}   # one to three leading digits
             (,[0-9]{3})* # any number of comma-delimited groups of 3 digits
             (\.[0-9]+)?  # optional decimal followed by one or more digits
          """,
        re.U | re.X)

    _contraction_endings = u'tsdTSD'

    def __init__(self):
        """Set rule priority and name. """
        Rule.__init__(self, 60,
                      "Separate punctuation (other than periods, apostrophes "
                      "not being used as quote marks, and single hypens) "
                      "into separate tokens.")

    def apply(self, ea):
        changed = False
        for token in ea.tokens:
            if token.non_printing or len(token.str) < 2 or token.is_URL:
                continue
            # get a list of match objects for embedded decimal numbers
            number_mos = [
                mo for mo in
                PunctSplitRule.embedded_decimal_number_re.finditer(token.str)]
            for i, char in enumerate(token.str):
                # DotSplitRule handles periods
                if char == u'.':
                    continue
                # ignore non-punctuation characters
                if not unicodedata.category(char).startswith(u'P'):
                    continue
                # found punctuation character. does it lie within any
                # span of embedded decimal numbers?
                skip = False
                for mo in number_mos:
                    if mo.start() <= i < mo.end():
                        skip = True
                        break
                if skip:
                    continue

                # Found punctuation character, and it is not embedded
                # within a number as a thousands separator or a decimal
                # point. Check to see if it is an apostrophe in a
                # contraction.
                if (char == u"'" and token.str[i + 1:] in
                    PunctSplitRule._contraction_endings):
                        continue

                # Don't split single hyphens, but do split runs of
                # hyphens
                if char == u'-':
                    # don't split trailing hyphen
                    if i == len(token.str) - 1:
                        continue
                    # don't split single embedded hyphen
                    if token.str[i + 1] != u'-':
                        continue
                    # we've found 2 or more hyphens in a row. split them
                    # into their own token.
                    if split_token_at_delim('PunctSplitRule', ea.tokens,
                                            ea.tokens.index(token), u'-', True):
                        changed = True
                        break
                    continue

                # Don't split an asterisk at the start of a token.
                if char == u'*' and i == 0:
                    continue

                # Split the token at this point.
                logging.debug(
                    u"PunctSplitRule splitting '{}' at {}".format(
                        token.str, i))
                split_token_at_index(
                    self, ea.tokens, ea.tokens.index(token), i, True)
                changed = True
                break
        return changed


class AlphaNumSplitRule(Rule):
    """Split alphanumeric sequences.
    """

    phase = INITIAL_PHASE

    def __init__(self):
        Rule.__init__(self, 70,
                      "Split conjoined words and "
                      "numbers into separate tokens.")

    def apply(self, ea):
        # | case | input     | output     |
        # |------+-----------+------------|
        # |    1 | 10am      | 10 am      |
        # |    2 | 10.00am   | 10.00 am   |
        # |    3 | 10:00am   | 10:00 am   |
        # |    4 | 10:00a.m. | 10:00 a.m. |
        # |    5 | 500foo    | 500 foo    |
        # |    6 | bar200    | bar 200    |
        # |    7 | ksh.1000  | ksh. 1000  |
        # |    8 | 30s       | 30s        |
        # |    9 | 14th      | 14th       |
        # |   10 | 2nd       | 2nd        |
        # |   11 | 43rd      | 43rd       |
        # |   12 | 1,200.    | 1,200 .    |
        # |   13 | 1,500.00  | 1,500.00   |
        changed = False
        for token in ea.tokens:
            # skip non-printing, URL, and short tokens
            if token.non_printing or len(token.str) < 2 or token.is_URL:
                continue
            mo = None
            if token.str[0].isalpha():
                # starts with an alpha char, split at first digit.
                mo = re.search(ur'\d', token.str)
            elif token.str[0].isdigit():
                # if it starts with a digit, split at first alpha, except
                # for cases 8 through 11 in the table above.
                if re.match(ur'[1-9][0-9]*0s', token.str):
                    # case 8
                    continue
                if token.is_alphanumeric_ordinal:
                    # cases 9-11
                    continue
                # case 12, note $ is for case 13
                mo = re.match(ur'[1-9][0-9]{,2}(?:,[0-9]{3})*\.(?:[^0-9]|$)',
                              token.str)
                if mo:
                    # reposition at period
                    mo = re.search(ur'\.', token.str)
                else:
                    # split at first alpha
                    mo = re.search(ur'[a-zA-Z]', token.str)
            if mo:
                logging.debug(u"AlphaNumSplitRule '{}' at {}".format(
                        token.str, mo.start()))
                split_token_at_index(self, ea.tokens, ea.tokens.index(token),
                                     mo.start(), False)
                changed = True
        return changed


class SpellDigitsRule(Rule):
    """Spell out numbers 1..9.

    Single digit positive numbers should not be spelled out if they:
    - are followed by '%'
    - appear to be part of an address.
    - are part of a  numbered list "1. foo 2. bar 3. baz
    """

    phase = INITIAL_PHASE

    spelled_digits = [
        u'one',
        u'two',
        u'three',
        u'four',
        u'five',
        u'six',
        u'seven',
        u'eight',
        u'nine']

    def __init__(self):
        """Set rule priority and name. """
        Rule.__init__(self, 80,
                      "Spell out single digit numbers.")

    def apply(self, ea):
        """Return True if any tokens are converted from digits to
        spelled numbers."""
        changed = False
        for i, token in enumerate(ea.tokens):
            # ignore tokens that aren't single digits
            if (token.non_printing or
                not token.has_digits or len(token.str) != 1):
                continue
            # token string is a single digit; get its integer equivalent
            digit_value = int(token.str)
            # '0' doesn't get spelled out
            if digit_value == 0:
                continue
            # token is a digit 1..9, but it should only be spelled out
            # in some contexts. Get the tokens immediately preceding and
            # following it so they can be checked.
            prev_token, next_token = get_neighbors(ea.tokens, i)

            # don't spell out percentages, i.e. we want the final text
            # to have "7%" not "seven %"
            if next_token and next_token.str == '%':
                continue

            # don't spell out single-digit currency values, i.e. don't
            # change "$1" to "$ one".
            if (prev_token and prev_token.is_currency_term or
                next_token and next_token.is_currency_term):
                continue

            # ok to spell out the digit; look up spelling
            logging.debug('SpellDigitsRule changing {} to {}'.format(
                token.str, SpellDigitsRule.spelled_digits[digit_value - 1]))
            token.str = SpellDigitsRule.spelled_digits[digit_value - 1]
            changed = True
        return changed


class DelimitThousandsRule(Rule):
    """Insert comma separators in currency values larger than 4 digits.
    """
    phase = INITIAL_PHASE

    _splittable_number_re = re.compile(ur'^[1-9][0-9]{4,}(\.[0-9]{2})?$', re.U)

    def __init__(self):
        Rule.__init__(self, 90,
                      "Format numbers which express amounts of currency.")

    @staticmethod
    def _digit_group_callback(match_obj):
        return match_obj.group(1) + ',' + match_obj.group(2)

    def _separate_thousands(self, token):
        changed = False
        original_token_str = token.str
        new_str = re.sub(ur'(\d)(\d{3})\b',
                         DelimitThousandsRule._digit_group_callback,
                         token.str)
        while new_str != token.str:
            token.str = new_str
            new_str = re.sub(ur'(\d)(\d{3})\b',
                             DelimitThousandsRule._digit_group_callback,
                             token.str)
        if original_token_str != token.str:
            changed = True
            logging.debug(u'DelimitThousandsRule changed {} to {}'.format(
                    original_token_str, token.str))
        return changed

    def apply(self, ea):
        changed = False
        for i, token in enumerate(ea.tokens):
            if token.non_printing:
                continue
            if not DelimitThousandsRule._splittable_number_re.match(token.str):
                continue
            # is preceding or following token recognized as a currency
            # symbol, ISO currency abbreviation, or term?
            if (i > 0 and ea.tokens[i - 1].is_currency_term or
                i < len(ea.tokens) - 1 and  ea.tokens[i + 1].is_currency_term):
                if self._separate_thousands(token):
                    changed = True
        return changed


class AccreteNumbersRule(Rule):
    """Merge consecutive tokens that together make a formatted decimal number.
    """
    phase = INITIAL_PHASE

    mergeable_number_re = re.compile(
        ur"""(^
               [0-9]{3}       # three leading digits, may start with 0
               (,[0-9]{3})+   # followed by one or more groups of comma-
                              # delimited numbers
               (\.[0-9]{2})?  # optionally followed by two decimal places
             $)
             |  # or an integer without delimiters
             (^
               ([0-9]{3})+ # one or more groups of 3 digits
             $)
          """,
        re.UNICODE | re.VERBOSE)

    def __init__(self):
        Rule.__init__(self, 100, "Remove spaces from numbers.")

    def _concat(self, tokens, start_idx, num):
        """Concatenate `num` elements of `tokens` starting at index
        `start_idx`.
        """
        logging.debug(u'AccreteNumbersRule concatenating %s',
                      tokens[start_idx:start_idx + num])
        assert(len(tokens) > 1)
        # first get the concatenated string
        concat_str = u''.join([t.str for t in
                               tokens[start_idx:start_idx + num]])
        logging.debug('new string "' + concat_str + '"')
        tokens[start_idx].str = concat_str
        tokens[start_idx].cend = tokens[start_idx + num - 1].cend
        # now delete the tokens whose contents were concatenated with
        # the token at start_idx.
        del tokens[start_idx + 1:start_idx + num]

    def apply(self, ea):
        changed = False
        for i, token in enumerate(ea.tokens):
            if token.non_printing or not token.has_digits:
                continue
            if not token.is_delimited_integer:
                continue
            right = get_right_neighbor(ea.tokens, i)
            if not right:
                continue
            # Can merge with right if it is a 3 digit or longer number,
            # optionally containing delimiting commas and a decimal
            # point.
            if AccreteNumbersRule.mergeable_number_re.match(right.str):
                self._concat(ea.tokens, i, 2)
                changed = True
                break
            # can also merge if next token (right) is a comma and the
            # one that follows it is a mergeable number
            if right.str == u',':
                right2 = get_right_neighbor(ea.tokens, i + 1)
                if AccreteNumbersRule.mergeable_number_re.match(right2.str):
                    self._concat(ea.tokens, i, 3)
                    changed = True
        return changed


class CurrencyOrderRule(Rule):
    """Require that ISO currency abbreviations come *after* the
    associated numbers."""

    phase = INITIAL_PHASE

    def __init__(self):
        Rule.__init__(
            self, 110,
            "Put currency abbreviations after the numbers they describe")

    def apply(self, ea):
        changed = False
        for i, token in enumerate(ea.tokens):
            if token.non_printing or not token.is_ISO_currency:
                continue
            # token is a 3-letter ISO currency abbreviation. If the next
            # token is a number, swap them, UNLESS the previous token is
            # also a number.
            left, right = get_neighbors(ea.tokens, i)
            if right and right.has_digits:
                if not left or not left.is_delimited_decimal:
                    logging.debug(
                        u'CurrencyOrderRule swapping {} and {}'.format(
                            token.str, right.str))
                    token.str, right.str = right.str, token.str
                    changed = True
                    break
        return changed


def currency_name_match(s1, s2):
    """Return True if s1 and s2 are the same currency name, even if one
    is plural and the other is not."""
    logging.debug('matching {} vs. {}'.format(s1, s2))
    s1 = s1.lower()
    s2 = s2.lower()
    if s1 == s2:
        return True
    if s1 + 's' == s2:
        return True
    if s1 == s2 + 's':
        return True
    return False


class ISOCurrencyRule(Rule):
    """Spell out ISO currency abbreviations.
    """

    phase = INITIAL_PHASE

    def __init__(self):
        Rule.__init__(
            self, 120,
            "Spell out the first occurrence of an ISO currency abbreviation.")

    def apply(self, ea):
        changed = False
        for i, token in enumerate(ea.tokens):
            if token.non_printing:
                continue
            # token is an ISO currency abbreviation like 'PHP' or 'AZN'.
            # If the transform returned by this code has already
            # processed it, it will have a flag set on it.
            if getattr(token, 'ISO_currency_expanded', False):
                # exit because the currency abbreviation should only be
                # expanded once.
                break

            # if token doesn't match a 3-letter ISO currency
            # abbreviation, skip it.
            if not token.is_ISO_currency:
                continue

            # to be considered a currency abbreviation, a token must be
            # preceded or followed by a number. Look at the tokens
            # immediately preceding and following the current one.
            prev_token, next_token = get_neighbors(ea.tokens, i)
            if (not (prev_token and prev_token.has_digits) and
                not (next_token and next_token.has_digits)):
                continue

            # check preceding and following tokens to see if the source
            # text spelled out this abbreviation already. Both of these
            # should be recognized:
            #   100 PHP (Philippine peso)
            #   100 Philippine peso (PHP)
            prev_alpha_token, next_alpha_token = get_neighbors(
                ea.tokens, i, 'is_alpha')
            currency_name = pycountry.currencies.get(
                letter=token.str.upper()).name
            name_words = currency_name.split()
            if (prev_alpha_token and
                currency_name_match(prev_alpha_token.str, name_words[-1]) or
                next_alpha_token and
                currency_name_match(next_alpha_token.str, name_words[0])):
                logging.debug(u'ISOCurrencyRule marking {} as expanded'.format(
                        token.str))
                token.ISO_currency_expanded = True
                changed = True
                break

            if token.str.upper() == u'USD':
                # On the Kiva website, loans are displayed in US
                # currency, which is denoted using the '$' currency
                # symbol. The description text should use the same
                # format, i.e., "$700" instead of "700 US Dollar (USD)".
                #
                # At this point at least one of 'prev_token' and
                # 'next_token' has digits in it. If both have digits, do
                # nothing because it's ambiguous which one the 'USD'
                # describes.
                if prev_token and prev_token.has_digits:
                    if next_token and next_token.has_digits:
                        continue
                    logging.debug(
                        u'ISOCurrencyRule prefixing {} '
                        'with $ and deleting {}'.format(prev_token,
                                                        ea.tokens[i - 1]))
                    token.str = '$' + prev_token.str
                    del ea.tokens[i - 1]
                    changed = True
                else:
                    # swap them first
                    logging.debug(u'ISOCurrencyRule swapping {} and {}'.format(
                            prev_token, token))
                    prev_token.str, token.str = token.str, prev_token.str
                    changed = True
            else:
                # this must be set to avoid infinite loop
                token.ISO_currency_expanded = True
                # insert tokens for the expanded currency abbreviation
                # and a left paren before the existing abbreviation
                # token.
                for new_token in map(Token, pycountry.currencies.get(
                        letter=token.str.upper()).name.split()):
                    logging.debug(u'ISOCurrencyRule inserting ' +
                                  new_token.str)
                    ea.tokens.insert(i, new_token)
                    i += 1
                logging.debug(u'ISOCurrencyRule inserting ( before ' +
                              ea.tokens[i].str)
                ea.tokens.insert(i, Token(u'('))
                logging.debug(u'ISOCurrencyRule inserting ) after ' +
                              ea.tokens[i + 1].str)
                ea.tokens.insert(i + 2, Token(u')'))
                changed = True
            # Exit the loop here because only the first abbreviation
            # should be spelled out.
            break
        return changed

#TODO:
# spell out sentence-initial numbers

# ---------------------------------------------------------------------------
#
# Part-of-Speech Phase rules.
#
# These rules expect tokens to have part-of-speech tags.
#
# ---------------------------------------------------------------------------


class DelimitSentencesRule(Rule):
    """Insert delimiter tokens between beginning and end of sentences.
    """

    phase = POS_PHASE

    def __init__(self):
        Rule.__init__(
            self, 200,
            "Surround every sentence with a sentence-delimiter token.")

    def apply(self, ea):
        """Return a transform that will insert the delimiter tokens.

        This rule is only intended to run once. It will disable itself
        after the first run. If it detects any pre-existing sentence
        delimiter tokens, it will return an empty list.
        """
        sentence_delim_token = Token('*EOS*')
        sentence_delim_token.sentence_delim = True
        changed = False
        i = 0
        while i < len(ea.tokens):
            # do nothing if this rule has ever been run.
            if ea.tokens[i].sentence_delim:
                self.enabled = False
                break
            if '.' in ea.tokens[i].pos:
                ea.tokens.insert(i + 1, sentence_delim_token)
                i += 1  # skip over inserted token
            i += 1
        return changed


# ---------------------------------------------------------------------------
#
# Parsed Phase rules.
#
# These rules expect ea.parses to be valid.
#
# ---------------------------------------------------------------------------

class YearOldRule(Rule):
    """Change 'xx years old' and 'xx year old' to 'xx-year-old' as
    appropriate.
    """

    phase = PARSED_PHASE

    def __init__(self):
        Rule.__init__(
            self, 300,
            "Fix incorrect plural and lack of hyphens in phrases "
            "like '20 years old man'.")

    def apply(self, ea):
        # search tokens for "years old"
        for sent in ea.sentences:
            years_idx = sent.find_sequence(u'years old')
            if years_idx == None:
                years_idx = sent.find_sequence(u'years - old')
            if years_idx == None:
                continue
            # get the node whose only child is the token 'years'
            years_node = sent.parse.node_from_token(ea.tokens[years_idx])
            if years_node.parent.name != 'plur_noun_orule':
                continue
            make_singular = False
        # She is 42 years old.
        # root_informal
        #   subjh
        #     bare_npq
        #       she
        #         <She 0:3>
        #     hcomp
        #       be_c_is
        #         <is 4:6>
        #       npadv
        #         appos
        #           bare_np
        #             adjn
        #               attr_adj_verb_psv_part
        #                 generic_trans_verb_pas
        #                   <42 7:9>
        #               plur_noun_orule
        #                 year_n1
        #                   <years 10:15>
        #           proper_np
        #             adjn
        #               old_a1
        #                 <old 16:19>
        #               noptcomp
        #                 generic_year_ne
        #                   <. 19:20>


            # nadj_rr
            #   measure_np
            #     generic_number
            #       <51 2:4>
            #     plur_noun_orule
            #       year_n1
            #         <years 5:10>
            #   npadv
            try:
                make_singular = years_node.parent.parent.parent.children[1].name == 'npadv'
                if make_singular:
                    logging.debug('make_singular case 1')
            except:
                pass
            # npadv_mnp
            #   adjh_s_xp
            #     a_one_adj
            #       <A 0:1>
            #     measure_np
            #       generic_card_ne
            #         <51 2:4>
            #       plur_noun_orule
            #         year_n1
            #           <years 5:10>
            if not make_singular:
                try:
                    make_singular = years_node.parent.parent.parent.parent.name == 'npadv_mnp'
                    if make_singular:
                        logging.debug('make_singular case 2')
                except:
                    pass
            # appos
            #   bare_np
            #     plur_noun_orule
            #       year_n1
            #         <years 5:10>
            if not make_singular:
                try:
                    make_singular = years_node.parent.parent.parent.name == 'appos'
                    if make_singular:
                        logging.debug('make_singular case 3')
                except:
                    pass
            # She is a 42-year old farmer.
            # frag_np
            #   bare_np
            #     punct_hinit
            #       plur_noun_orule
            #         year_n1
            #           <years 11:16>
            #       s_dash_pct
            #         <- 16:17>
            if not make_singular:
                try:
                    make_singular = (
                        years_node.parent.parent.parent.name == 'bare_np' and
                        years_node.parent.parent.children[1].name == 's_dash_pct')
                    if make_singular:
                        logging.debug('make_singular case 4')
                except:
                    pass

            if make_singular:
                years_token = years_node.children[0]
                original = unicode(years_token)
                years_token.str = u'year'
                logging.debug(u'YearOldRule changed {} to {}'.format(
                        original, unicode(years_token)))
        return False
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.