forked from rohanag/StockMarketSentimentAnalysis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsnowball.py
3728 lines (3071 loc) · 147 KB
/
snowball.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
# -*- coding: utf-8 -*-
#
# Natural Language Toolkit: Snowball Stemmer
#
# Copyright (C) 2001-2012 NLTK Project
# Author: Peter Michael Stahl <pemistahl@gmail.com>
# Peter Ljunglof <peter.ljunglof@heatherleaf.se> (revisions)
# Algorithms: Dr Martin Porter <martin@tartarus.org>
# URL: <http://www.nltk.org/>
# For license information, see LICENSE.TXT
u"""
Snowball stemmers and appendant demo function
This module provides a port of the Snowball stemmers
developed by Martin Porter.
There is also a demo function demonstrating the different
algorithms. It can be invoked directly on the command line.
For more information take a look into the class SnowballStemmer.
"""
from nltk.corpus import stopwords
from nltk.stem import porter
from api import StemmerI
class SnowballStemmer(StemmerI):
u"""
Snowball Stemmer
At the moment, this port is able to stem words from fourteen
languages: Danish, Dutch, English, Finnish, French, German,
Hungarian, Italian, Norwegian, Portuguese, Romanian, Russian,
Spanish and Swedish.
Furthermore, there is also the original English Porter algorithm:
Porter, M. \"An algorithm for suffix stripping.\"
Program 14.3 (1980): 130-137.
The algorithms have been developed by Martin Porter.
These stemmers are called Snowball, because he invented
a programming language with this name for creating
new stemming algorithms. There is more information available
at http://snowball.tartarus.org/
The stemmer is invoked as shown below:
>>> from nltk.stem import SnowballStemmer
>>> SnowballStemmer.languages # See which languages are supported
('danish', 'dutch', 'english', 'finnish', 'french', 'german', 'hungarian',
'italian', 'norwegian', 'porter', 'portuguese', 'romanian', 'russian',
'spanish', 'swedish')
>>> stemmer = SnowballStemmer("german") # Choose a language
>>> stemmer.stem(u"Autobahnen") # Stem a word
u'autobahn'
Invoking the stemmers that way is useful if you do not know the
language to be stemmed at runtime. Alternatively, if you already know
the language, then you can invoke the language specific stemmer directly:
>>> from nltk.stem.snowball import GermanStemmer
>>> stemmer = GermanStemmer()
>>> stemmer.stem(u"Autobahnen")
u'autobahn'
Create a language specific instance of the Snowball stemmer.
:param language: The language whose subclass is instantiated.
:type language: str or unicode
:param ignore_stopwords: If set to True, stopwords are
not stemmed and returned unchanged.
Set to False by default.
:type ignore_stopwords: bool
:raise ValueError: If there is no stemmer for the specified
language, a ValueError is raised.
"""
languages = ("danish", "dutch", "english", "finnish", "french", "german",
"hungarian", "italian", "norwegian", "porter", "portuguese",
"romanian", "russian", "spanish", "swedish")
def __init__(self, language, ignore_stopwords=False):
if language not in self.languages:
raise ValueError(u"The language '%s' is not supported." % language)
stemmerclass = globals()[language.capitalize() + "Stemmer"]
self.stemmer = stemmerclass(ignore_stopwords)
self.stem = self.stemmer.stem
self.stopwords = self.stemmer.stopwords
class _LanguageSpecificStemmer(StemmerI):
u"""
This helper subclass offers the possibility
to invoke a specific stemmer directly.
This is useful if you already know the language to be stemmed at runtime.
Create an instance of the Snowball stemmer.
:param ignore_stopwords: If set to True, stopwords are
not stemmed and returned unchanged.
Set to False by default.
:type ignore_stopwords: bool
"""
def __init__(self, ignore_stopwords=False):
# The language is the name of the class, minus the final "Stemmer".
language = type(self).__name__.lower()
if language.endswith("stemmer"):
language = language[:-7]
self.stopwords = set()
if ignore_stopwords:
try:
for word in stopwords.words(language):
self.stopwords.add(word.decode("utf-8"))
except IOError:
raise ValueError("%r has no list of stopwords. Please set"
" 'ignore_stopwords' to 'False'." % self)
def __repr__(self):
u"""
Print out the string representation of the respective class.
"""
return "<%s>" % type(self).__name__
class PorterStemmer(_LanguageSpecificStemmer, porter.PorterStemmer):
"""
A word stemmer based on the original Porter stemming algorithm.
Porter, M. \"An algorithm for suffix stripping.\"
Program 14.3 (1980): 130-137.
A few minor modifications have been made to Porter's basic
algorithm. See the source code of the module
nltk.stem.porter for more information.
"""
def __init__(self, ignore_stopwords=False):
_LanguageSpecificStemmer.__init__(self, ignore_stopwords)
porter.PorterStemmer.__init__(self)
class _ScandinavianStemmer(_LanguageSpecificStemmer):
u"""
This subclass encapsulates a method for defining the string region R1.
It is used by the Danish, Norwegian, and Swedish stemmer.
"""
def _r1_scandinavian(self, word, vowels):
u"""
Return the region R1 that is used by the Scandinavian stemmers.
R1 is the region after the first non-vowel following a vowel,
or is the null region at the end of the word if there is no
such non-vowel. But then R1 is adjusted so that the region
before it contains at least three letters.
:param word: The word whose region R1 is determined.
:type word: str or unicode
:param vowels: The vowels of the respective language that are
used to determine the region R1.
:type vowels: unicode
:return: the region R1 for the respective word.
:rtype: unicode
:note: This helper method is invoked by the respective stem method of
the subclasses DanishStemmer, NorwegianStemmer, and
SwedishStemmer. It is not to be invoked directly!
"""
r1 = u""
for i in xrange(1, len(word)):
if word[i] not in vowels and word[i-1] in vowels:
if len(word[:i+1]) < 3 and len(word[:i+1]) > 0:
r1 = word[3:]
elif len(word[:i+1]) >= 3:
r1 = word[i+1:]
else:
return word
break
return r1
class _StandardStemmer(_LanguageSpecificStemmer):
u"""
This subclass encapsulates two methods for defining the standard versions
of the string regions R1, R2, and RV.
"""
def _r1r2_standard(self, word, vowels):
u"""
Return the standard interpretations of the string regions R1 and R2.
R1 is the region after the first non-vowel following a vowel,
or is the null region at the end of the word if there is no
such non-vowel.
R2 is the region after the first non-vowel following a vowel
in R1, or is the null region at the end of the word if there
is no such non-vowel.
:param word: The word whose regions R1 and R2 are determined.
:type word: str or unicode
:param vowels: The vowels of the respective language that are
used to determine the regions R1 and R2.
:type vowels: unicode
:return: (r1,r2), the regions R1 and R2 for the respective word.
:rtype: tuple
:note: This helper method is invoked by the respective stem method of
the subclasses DutchStemmer, FinnishStemmer,
FrenchStemmer, GermanStemmer, ItalianStemmer,
PortugueseStemmer, RomanianStemmer, and SpanishStemmer.
It is not to be invoked directly!
:note: A detailed description of how to define R1 and R2
can be found at http://snowball.tartarus.org/texts/r1r2.html
"""
r1 = u""
r2 = u""
for i in xrange(1, len(word)):
if word[i] not in vowels and word[i-1] in vowels:
r1 = word[i+1:]
break
for i in xrange(1, len(r1)):
if r1[i] not in vowels and r1[i-1] in vowels:
r2 = r1[i+1:]
break
return (r1, r2)
def _rv_standard(self, word, vowels):
u"""
Return the standard interpretation of the string region RV.
If the second letter is a consonant, RV is the region after the
next following vowel. If the first two letters are vowels, RV is
the region after the next following consonant. Otherwise, RV is
the region after the third letter.
:param word: The word whose region RV is determined.
:type word: str or unicode
:param vowels: The vowels of the respective language that are
used to determine the region RV.
:type vowels: unicode
:return: the region RV for the respective word.
:rtype: unicode
:note: This helper method is invoked by the respective stem method of
the subclasses ItalianStemmer, PortugueseStemmer,
RomanianStemmer, and SpanishStemmer. It is not to be
invoked directly!
"""
rv = u""
if len(word) >= 2:
if word[1] not in vowels:
for i in xrange(2, len(word)):
if word[i] in vowels:
rv = word[i+1:]
break
elif word[:2] in vowels:
for i in xrange(2, len(word)):
if word[i] not in vowels:
rv = word[i+1:]
break
else:
rv = word[3:]
return rv
class DanishStemmer(_ScandinavianStemmer):
u"""
The Danish Snowball stemmer.
:cvar __vowels: The Danish vowels.
:type __vowels: unicode
:cvar __consonants: The Danish consonants.
:type __consonants: unicode
:cvar __double_consonants: The Danish double consonants.
:type __double_consonants: tuple
:cvar __s_ending: Letters that may directly appear before a word final 's'.
:type __s_ending: unicode
:cvar __step1_suffixes: Suffixes to be deleted in step 1 of the algorithm.
:type __step1_suffixes: tuple
:cvar __step2_suffixes: Suffixes to be deleted in step 2 of the algorithm.
:type __step2_suffixes: tuple
:cvar __step3_suffixes: Suffixes to be deleted in step 3 of the algorithm.
:type __step3_suffixes: tuple
:note: A detailed description of the Danish
stemming algorithm can be found under
http://snowball.tartarus.org/algorithms/danish/stemmer.html
"""
# The language's vowels and other important characters are defined.
__vowels = u"aeiouy\xE6\xE5\xF8"
__consonants = u"bcdfghjklmnpqrstvwxz"
__double_consonants = (u"bb", u"cc", u"dd", u"ff", u"gg", u"hh", u"jj",
u"kk", u"ll", u"mm", u"nn", u"pp", u"qq", u"rr",
u"ss", u"tt", u"vv", u"ww", u"xx", u"zz")
__s_ending = u"abcdfghjklmnoprtvyz\xE5"
# The different suffixes, divided into the algorithm's steps
# and organized by length, are listed in tuples.
__step1_suffixes = (u"erendes", u"erende", u"hedens", u"ethed",
u"erede", u"heden", u"heder", u"endes",
u"ernes", u"erens", u"erets", u"ered",
u"ende", u"erne", u"eren", u"erer", u"heds",
u"enes", u"eres", u"eret", u"hed", u"ene", u"ere",
u"ens", u"ers", u"ets", u"en", u"er", u"es", u"et",
u"e", u"s")
__step2_suffixes = (u"gd", u"dt", u"gt", u"kt")
__step3_suffixes = (u"elig", u"l\xF8st", u"lig", u"els", u"ig")
def stem(self, word):
u"""
Stem a Danish word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
# Every word is put into lower case for normalization.
word = word.lower()
if word in self.stopwords:
return word
# After this, the required regions are generated
# by the respective helper method.
r1 = self._r1_scandinavian(word, self.__vowels)
# Then the actual stemming process starts.
# Every new step is explicitly indicated
# according to the descriptions on the Snowball website.
# STEP 1
for suffix in self.__step1_suffixes:
if r1.endswith(suffix):
if suffix == u"s":
if word[-2] in self.__s_ending:
word = word[:-1]
r1 = r1[:-1]
else:
word = word[:-len(suffix)]
r1 = r1[:-len(suffix)]
break
# STEP 2
for suffix in self.__step2_suffixes:
if r1.endswith(suffix):
word = word[:-1]
r1 = r1[:-1]
break
# STEP 3
if r1.endswith(u"igst"):
word = word[:-2]
r1 = r1[:-2]
for suffix in self.__step3_suffixes:
if r1.endswith(suffix):
if suffix == u"l\xF8st":
word = word[:-1]
r1 = r1[:-1]
else:
word = word[:-len(suffix)]
r1 = r1[:-len(suffix)]
if r1.endswith(self.__step2_suffixes):
word = word[:-1]
r1 = r1[:-1]
break
# STEP 4: Undouble
for double_cons in self.__double_consonants:
if word.endswith(double_cons) and len(word) > 3:
word = word[:-1]
break
return word
class DutchStemmer(_StandardStemmer):
u"""
The Dutch Snowball stemmer.
:cvar __vowels: The Dutch vowels.
:type __vowels: unicode
:cvar __step1_suffixes: Suffixes to be deleted in step 1 of the algorithm.
:type __step1_suffixes: tuple
:cvar __step3b_suffixes: Suffixes to be deleted in step 3b of the algorithm.
:type __step3b_suffixes: tuple
:note: A detailed description of the Dutch
stemming algorithm can be found under
http://snowball.tartarus.org/algorithms/dutch/stemmer.html
"""
__vowels = u"aeiouy\xE8"
__step1_suffixes = (u"heden", u"ene", u"en", u"se", u"s")
__step3b_suffixes = (u"baar", u"lijk", u"bar", u"end", u"ing", u"ig")
def stem(self, word):
u"""
Stem a Dutch word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
word = word.lower()
if word in self.stopwords:
return word
step2_success = False
# Vowel accents are removed.
word = (word.replace(u"\xE4", u"a").replace(u"\xE1", u"a")
.replace(u"\xEB", u"e").replace(u"\xE9", u"e")
.replace(u"\xED", u"i").replace(u"\xEF", u"i")
.replace(u"\xF6", u"o").replace(u"\xF3", u"o")
.replace(u"\xFC", u"u").replace(u"\xFA", u"u"))
# An initial 'y', a 'y' after a vowel,
# and an 'i' between self.__vowels is put into upper case.
# As from now these are treated as consonants.
if word.startswith(u"y"):
word = u"".join((u"Y", word[1:]))
for i in xrange(1, len(word)):
if word[i-1] in self.__vowels and word[i] == u"y":
word = u"".join((word[:i], u"Y", word[i+1:]))
for i in xrange(1, len(word)-1):
if (word[i-1] in self.__vowels and word[i] == u"i" and
word[i+1] in self.__vowels):
word = u"".join((word[:i], u"I", word[i+1:]))
r1, r2 = self._r1r2_standard(word, self.__vowels)
# R1 is adjusted so that the region before it
# contains at least 3 letters.
for i in xrange(1, len(word)):
if word[i] not in self.__vowels and word[i-1] in self.__vowels:
if len(word[:i+1]) < 3 and len(word[:i+1]) > 0:
r1 = word[3:]
elif len(word[:i+1]) == 0:
return word
break
# STEP 1
for suffix in self.__step1_suffixes:
if r1.endswith(suffix):
if suffix == u"heden":
word = u"".join((word[:-5], u"heid"))
r1 = u"".join((r1[:-5], u"heid"))
if r2.endswith(u"heden"):
r2 = u"".join((r2[:-5], u"heid"))
elif (suffix in (u"ene", u"en") and
not word.endswith(u"heden") and
word[-len(suffix)-1] not in self.__vowels and
word[-len(suffix)-3:-len(suffix)] != u"gem"):
word = word[:-len(suffix)]
r1 = r1[:-len(suffix)]
r2 = r2[:-len(suffix)]
if word.endswith((u"kk", u"dd", u"tt")):
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
elif (suffix in (u"se", u"s") and
word[-len(suffix)-1] not in self.__vowels and
word[-len(suffix)-1] != u"j"):
word = word[:-len(suffix)]
r1 = r1[:-len(suffix)]
r2 = r2[:-len(suffix)]
break
# STEP 2
if r1.endswith(u"e") and word[-2] not in self.__vowels:
step2_success = True
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
if word.endswith((u"kk", u"dd", u"tt")):
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
# STEP 3a
if r2.endswith(u"heid") and word[-5] != u"c":
word = word[:-4]
r1 = r1[:-4]
r2 = r2[:-4]
if (r1.endswith(u"en") and word[-3] not in self.__vowels and
word[-5:-2] != u"gem"):
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
if word.endswith((u"kk", u"dd", u"tt")):
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
# STEP 3b: Derivational suffixes
for suffix in self.__step3b_suffixes:
if r2.endswith(suffix):
if suffix in (u"end", u"ing"):
word = word[:-3]
r2 = r2[:-3]
if r2.endswith(u"ig") and word[-3] != u"e":
word = word[:-2]
else:
if word.endswith((u"kk", u"dd", u"tt")):
word = word[:-1]
elif suffix == u"ig" and word[-3] != u"e":
word = word[:-2]
elif suffix == u"lijk":
word = word[:-4]
r1 = r1[:-4]
if r1.endswith(u"e") and word[-2] not in self.__vowels:
word = word[:-1]
if word.endswith((u"kk", u"dd", u"tt")):
word = word[:-1]
elif suffix == u"baar":
word = word[:-4]
elif suffix == u"bar" and step2_success:
word = word[:-3]
break
# STEP 4: Undouble vowel
if len(word) >= 4:
if word[-1] not in self.__vowels and word[-1] != u"I":
if word[-3:-1] in (u"aa", u"ee", u"oo", u"uu"):
if word[-4] not in self.__vowels:
word = u"".join((word[:-3], word[-3], word[-1]))
# All occurrences of 'I' and 'Y' are put back into lower case.
word = word.replace(u"I", u"i").replace(u"Y", u"y")
return word
class EnglishStemmer(_StandardStemmer):
u"""
The English Snowball stemmer.
:cvar __vowels: The English vowels.
:type __vowels: unicode
:cvar __double_consonants: The English double consonants.
:type __double_consonants: tuple
:cvar __li_ending: Letters that may directly appear before a word final 'li'.
:type __li_ending: unicode
:cvar __step0_suffixes: Suffixes to be deleted in step 0 of the algorithm.
:type __step0_suffixes: tuple
:cvar __step1a_suffixes: Suffixes to be deleted in step 1a of the algorithm.
:type __step1a_suffixes: tuple
:cvar __step1b_suffixes: Suffixes to be deleted in step 1b of the algorithm.
:type __step1b_suffixes: tuple
:cvar __step2_suffixes: Suffixes to be deleted in step 2 of the algorithm.
:type __step2_suffixes: tuple
:cvar __step3_suffixes: Suffixes to be deleted in step 3 of the algorithm.
:type __step3_suffixes: tuple
:cvar __step4_suffixes: Suffixes to be deleted in step 4 of the algorithm.
:type __step4_suffixes: tuple
:cvar __step5_suffixes: Suffixes to be deleted in step 5 of the algorithm.
:type __step5_suffixes: tuple
:cvar __special_words: A dictionary containing words
which have to be stemmed specially.
:type __special_words: dict
:note: A detailed description of the English
stemming algorithm can be found under
http://snowball.tartarus.org/algorithms/english/stemmer.html
"""
__vowels = u"aeiouy"
__double_consonants = (u"bb", u"dd", u"ff", u"gg", u"mm", u"nn",
u"pp", u"rr", u"tt")
__li_ending = u"cdeghkmnrt"
__step0_suffixes = (u"'s'", u"'s", u"'")
__step1a_suffixes = (u"sses", u"ied", u"ies", u"us", u"ss", u"s")
__step1b_suffixes = (u"eedly", u"ingly", u"edly", u"eed", u"ing", u"ed")
__step2_suffixes = (u'ization', u'ational', u'fulness', u'ousness',
u'iveness', u'tional', u'biliti', u'lessli',
u'entli', u'ation', u'alism', u'aliti', u'ousli',
u'iviti', u'fulli', u'enci', u'anci', u'abli',
u'izer', u'ator', u'alli', u'bli', u'ogi', u'li')
__step3_suffixes = (u'ational', u'tional', u'alize', u'icate', u'iciti',
u'ative', u'ical', u'ness', u'ful')
__step4_suffixes = (u'ement', u'ance', u'ence', u'able', u'ible', u'ment',
u'ant', u'ent', u'ism', u'ate', u'iti', u'ous',
u'ive', u'ize', u'ion', u'al', u'er', u'ic')
__step5_suffixes = (u"e", u"l")
__special_words = {u"skis" : u"ski",
u"skies" : u"sky",
u"dying" : u"die",
u"lying" : u"lie",
u"tying" : u"tie",
u"idly" : u"idl",
u"gently" : u"gentl",
u"ugly" : u"ugli",
u"early" : u"earli",
u"only" : u"onli",
u"singly" : u"singl",
u"sky" : u"sky",
u"news" : u"news",
u"howe" : u"howe",
u"atlas" : u"atlas",
u"cosmos" : u"cosmos",
u"bias" : u"bias",
u"andes" : u"andes",
u"inning" : u"inning",
u"innings" : u"inning",
u"outing" : u"outing",
u"outings" : u"outing",
u"canning" : u"canning",
u"cannings" : u"canning",
u"herring" : u"herring",
u"herrings" : u"herring",
u"earring" : u"earring",
u"earrings" : u"earring",
u"proceed" : u"proceed",
u"proceeds" : u"proceed",
u"proceeded" : u"proceed",
u"proceeding" : u"proceed",
u"exceed" : u"exceed",
u"exceeds" : u"exceed",
u"exceeded" : u"exceed",
u"exceeding" : u"exceed",
u"succeed" : u"succeed",
u"succeeds" : u"succeed",
u"succeeded" : u"succeed",
u"succeeding" : u"succeed"}
def stem(self, word):
u"""
Stem an English word and return the stemmed form.
:param word: The word that is stemmed.
:type word: str or unicode
:return: The stemmed form.
:rtype: unicode
"""
word = word.lower()
if word in self.stopwords or len(word) <= 2:
return word
elif word in self.__special_words:
return self.__special_words[word]
# Map the different apostrophe characters to a single consistent one
word = (word.replace(u"\u2019", u"\x27")
.replace(u"\u2018", u"\x27")
.replace(u"\u201B", u"\x27"))
if word.startswith(u"\x27"):
word = word[1:]
if word.startswith(u"y"):
word = "".join((u"Y", word[1:]))
for i in xrange(1, len(word)):
if word[i-1] in self.__vowels and word[i] == u"y":
word = "".join((word[:i], u"Y", word[i+1:]))
step1a_vowel_found = False
step1b_vowel_found = False
r1 = u""
r2 = u""
if word.startswith((u"gener", u"commun", u"arsen")):
if word.startswith((u"gener", u"arsen")):
r1 = word[5:]
else:
r1 = word[6:]
for i in xrange(1, len(r1)):
if r1[i] not in self.__vowels and r1[i-1] in self.__vowels:
r2 = r1[i+1:]
break
else:
r1, r2 = self._r1r2_standard(word, self.__vowels)
# STEP 0
for suffix in self.__step0_suffixes:
if word.endswith(suffix):
word = word[:-len(suffix)]
r1 = r1[:-len(suffix)]
r2 = r2[:-len(suffix)]
break
# STEP 1a
for suffix in self.__step1a_suffixes:
if word.endswith(suffix):
if suffix == u"sses":
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
elif suffix in (u"ied", u"ies"):
if len(word[:-len(suffix)]) > 1:
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
else:
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
elif suffix == u"s":
for letter in word[:-2]:
if letter in self.__vowels:
step1a_vowel_found = True
break
if step1a_vowel_found:
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
break
# STEP 1b
for suffix in self.__step1b_suffixes:
if word.endswith(suffix):
if suffix in (u"eed", u"eedly"):
if r1.endswith(suffix):
word = u"".join((word[:-len(suffix)], u"ee"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ee"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ee"))
else:
r2 = u""
else:
for letter in word[:-len(suffix)]:
if letter in self.__vowels:
step1b_vowel_found = True
break
if step1b_vowel_found:
word = word[:-len(suffix)]
r1 = r1[:-len(suffix)]
r2 = r2[:-len(suffix)]
if word.endswith((u"at", u"bl", u"iz")):
word = u"".join((word, u"e"))
r1 = u"".join((r1, u"e"))
if len(word) > 5 or len(r1) >=3:
r2 = u"".join((r2, u"e"))
elif word.endswith(self.__double_consonants):
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
elif ((r1 == u"" and len(word) >= 3 and
word[-1] not in self.__vowels and
word[-1] not in u"wxY" and
word[-2] in self.__vowels and
word[-3] not in self.__vowels)
or
(r1 == u"" and len(word) == 2 and
word[0] in self.__vowels and
word[1] not in self.__vowels)):
word = u"".join((word, u"e"))
if len(r1) > 0:
r1 = u"".join((r1, u"e"))
if len(r2) > 0:
r2 = u"".join((r2, u"e"))
break
# STEP 1c
if word[-1] in u"yY" and word[-2] not in self.__vowels and len(word) > 2:
word = u"".join((word[:-1], u"i"))
if len(r1) >= 1:
r1 = u"".join((r1[:-1], u"i"))
else:
r1 = u""
if len(r2) >= 1:
r2 = u"".join((r2[:-1], u"i"))
else:
r2 = u""
# STEP 2
for suffix in self.__step2_suffixes:
if word.endswith(suffix):
if r1.endswith(suffix):
if suffix == u"tional":
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
elif suffix in (u"enci", u"anci", u"abli"):
word = u"".join((word[:-1], u"e"))
if len(r1) >= 1:
r1 = u"".join((r1[:-1], u"e"))
else:
r1 = u""
if len(r2) >= 1:
r2 = u"".join((r2[:-1], u"e"))
else:
r2 = u""
elif suffix == u"entli":
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
elif suffix in (u"izer", u"ization"):
word = u"".join((word[:-len(suffix)], u"ize"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ize"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ize"))
else:
r2 = u""
elif suffix in (u"ational", u"ation", u"ator"):
word = u"".join((word[:-len(suffix)], u"ate"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ate"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ate"))
else:
r2 = u"e"
elif suffix in (u"alism", u"aliti", u"alli"):
word = u"".join((word[:-len(suffix)], u"al"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"al"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"al"))
else:
r2 = u""
elif suffix == u"fulness":
word = word[:-4]
r1 = r1[:-4]
r2 = r2[:-4]
elif suffix in (u"ousli", u"ousness"):
word = u"".join((word[:-len(suffix)], u"ous"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ous"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ous"))
else:
r2 = u""
elif suffix in (u"iveness", u"iviti"):
word = u"".join((word[:-len(suffix)], u"ive"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ive"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ive"))
else:
r2 = u"e"
elif suffix in (u"biliti", u"bli"):
word = u"".join((word[:-len(suffix)], u"ble"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ble"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ble"))
else:
r2 = u""
elif suffix == u"ogi" and word[-4] == u"l":
word = word[:-1]
r1 = r1[:-1]
r2 = r2[:-1]
elif suffix in (u"fulli", u"lessli"):
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
elif suffix == u"li" and word[-3] in self.__li_ending:
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
break
# STEP 3
for suffix in self.__step3_suffixes:
if word.endswith(suffix):
if r1.endswith(suffix):
if suffix == u"tional":
word = word[:-2]
r1 = r1[:-2]
r2 = r2[:-2]
elif suffix == u"ational":
word = u"".join((word[:-len(suffix)], u"ate"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ate"))
else:
r1 = u""
if len(r2) >= len(suffix):
r2 = u"".join((r2[:-len(suffix)], u"ate"))
else:
r2 = u""
elif suffix == u"alize":
word = word[:-3]
r1 = r1[:-3]
r2 = r2[:-3]
elif suffix in (u"icate", u"iciti", u"ical"):
word = u"".join((word[:-len(suffix)], u"ic"))
if len(r1) >= len(suffix):
r1 = u"".join((r1[:-len(suffix)], u"ic"))
else:
r1 = u""
if len(r2) >= len(suffix):