stemmer.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. from __future__ import unicode_literals
  2. """
  3. Implementation of Porter Stemming Algorithm from
  4. https://tartarus.org/martin/PorterStemmer/python.txt
  5. Note: The Python implementation returns different results than the JS
  6. version:
  7. - Stemming "lay" returns "lai" in Python, but "lay" in JS
  8. - Stemming "try" returns "try" in Python, but "tri" in JS
  9. Porter Stemming Algorithm
  10. This is the Porter stemming algorithm, ported to Python from the
  11. version coded up in ANSI C by the author. It may be be regarded
  12. as canonical, in that it follows the algorithm presented in
  13. Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
  14. no. 3, pp 130-137,
  15. only differing from it at the points maked --DEPARTURE-- below.
  16. See also http://www.tartarus.org/~martin/PorterStemmer
  17. The algorithm as described in the paper could be exactly replicated
  18. by adjusting the points of DEPARTURE, but this is barely necessary,
  19. because (a) the points of DEPARTURE are definitely improvements, and
  20. (b) no encoding of the Porter stemmer I have seen is anything like
  21. as exact as this version, even with the points of DEPARTURE!
  22. Vivake Gupta (v@nano.com)
  23. Release 1: January 2001
  24. Further adjustments by Santiago Bruno (bananabruno@gmail.com)
  25. to allow word input not restricted to one word per line, leading
  26. to:
  27. release 2: July 2008
  28. """
  29. from lunr.pipeline import Pipeline
  30. class PorterStemmer:
  31. def __init__(self):
  32. """The main part of the stemming algorithm starts here.
  33. b is a buffer holding a word to be stemmed. The letters are in b[k0],
  34. b[k0+1] ... ending at b[k]. In fact k0 = 0 in this demo program. k is
  35. readjusted downwards as the stemming progresses. Zero termination is
  36. not in fact used in the algorithm.
  37. Note that only lower case sequences are stemmed. Forcing to lower case
  38. should be done before stem(...) is called.
  39. """
  40. self.b = "" # buffer for word to be stemmed
  41. self.k = 0
  42. self.k0 = 0
  43. self.j = 0 # j is a general offset into the string
  44. def cons(self, i):
  45. """cons(i) is TRUE <=> b[i] is a consonant."""
  46. if (
  47. self.b[i] == "a"
  48. or self.b[i] == "e"
  49. or self.b[i] == "i"
  50. or self.b[i] == "o"
  51. or self.b[i] == "u"
  52. ):
  53. return 0
  54. if self.b[i] == "y":
  55. if i == self.k0:
  56. return 1
  57. else:
  58. return not self.cons(i - 1)
  59. return 1
  60. def m(self):
  61. """m() measures the number of consonant sequences between k0 and j.
  62. if c is a consonant sequence and v a vowel sequence, and <..>
  63. indicates arbitrary presence,
  64. <c><v> gives 0
  65. <c>vc<v> gives 1
  66. <c>vcvc<v> gives 2
  67. <c>vcvcvc<v> gives 3
  68. ....
  69. """
  70. n = 0
  71. i = self.k0
  72. while 1:
  73. if i > self.j:
  74. return n
  75. if not self.cons(i):
  76. break
  77. i = i + 1
  78. i = i + 1
  79. while 1:
  80. while 1:
  81. if i > self.j:
  82. return n
  83. if self.cons(i):
  84. break
  85. i = i + 1
  86. i = i + 1
  87. n = n + 1
  88. while 1:
  89. if i > self.j:
  90. return n
  91. if not self.cons(i):
  92. break
  93. i = i + 1
  94. i = i + 1
  95. def vowelinstem(self):
  96. """vowelinstem() is TRUE <=> k0,...j contains a vowel"""
  97. for i in range(self.k0, self.j + 1):
  98. if not self.cons(i):
  99. return 1
  100. return 0
  101. def doublec(self, j):
  102. """doublec(j) is TRUE <=> j,(j-1) contain a double consonant."""
  103. if j < (self.k0 + 1):
  104. return 0
  105. if self.b[j] != self.b[j - 1]:
  106. return 0
  107. return self.cons(j)
  108. def cvc(self, i):
  109. """cvc(i) is TRUE <=> i-2,i-1,i has the form consonant - vowel - consonant
  110. and also if the second c is not w,x or y. this is used when trying to
  111. restore an e at the end of a short e.g.
  112. cav(e), lov(e), hop(e), crim(e), but
  113. snow, box, tray.
  114. """
  115. if (
  116. i < (self.k0 + 2)
  117. or not self.cons(i)
  118. or self.cons(i - 1)
  119. or not self.cons(i - 2)
  120. ):
  121. return 0
  122. ch = self.b[i]
  123. if ch == "w" or ch == "x" or ch == "y":
  124. return 0
  125. return 1
  126. def ends(self, s):
  127. """ends(s) is TRUE <=> k0,...k ends with the string s."""
  128. length = len(s)
  129. if s[length - 1] != self.b[self.k]: # tiny speed-up
  130. return 0
  131. if length > (self.k - self.k0 + 1):
  132. return 0
  133. if self.b[self.k - length + 1 : self.k + 1] != s:
  134. return 0
  135. self.j = self.k - length
  136. return 1
  137. def setto(self, s):
  138. """setto(s) sets (j+1),...k to the characters in the string s, readjusting k."""
  139. length = len(s)
  140. self.b = self.b[: self.j + 1] + s + self.b[self.j + length + 1 :]
  141. self.k = self.j + length
  142. def r(self, s):
  143. """r(s) is used further down."""
  144. if self.m() > 0:
  145. self.setto(s)
  146. def step1ab(self):
  147. """step1ab() gets rid of plurals and -ed or -ing. e.g.
  148. caresses -> caress
  149. ponies -> poni
  150. ties -> ti
  151. caress -> caress
  152. cats -> cat
  153. feed -> feed
  154. agreed -> agree
  155. disabled -> disable
  156. matting -> mat
  157. mating -> mate
  158. meeting -> meet
  159. milling -> mill
  160. messing -> mess
  161. meetings -> meet
  162. """
  163. if self.b[self.k] == "s":
  164. if self.ends("sses"):
  165. self.k = self.k - 2
  166. elif self.ends("ies"):
  167. self.setto("i")
  168. elif self.b[self.k - 1] != "s":
  169. self.k = self.k - 1
  170. if self.ends("eed"):
  171. if self.m() > 0:
  172. self.k = self.k - 1
  173. elif (self.ends("ed") or self.ends("ing")) and self.vowelinstem():
  174. self.k = self.j
  175. if self.ends("at"):
  176. self.setto("ate")
  177. elif self.ends("bl"):
  178. self.setto("ble")
  179. elif self.ends("iz"):
  180. self.setto("ize")
  181. elif self.doublec(self.k):
  182. self.k = self.k - 1
  183. ch = self.b[self.k]
  184. if ch == "l" or ch == "s" or ch == "z":
  185. self.k = self.k + 1
  186. elif self.m() == 1 and self.cvc(self.k):
  187. self.setto("e")
  188. def step1c(self):
  189. """step1c() turns terminal y to i when there is another vowel in the stem."""
  190. if self.ends("y") and self.vowelinstem():
  191. self.b = self.b[: self.k] + "i" + self.b[self.k + 1 :]
  192. def step2(self):
  193. """step2() maps double suffices to single ones.
  194. so -ization ( = -ize plus -ation) maps to -ize etc. note that the
  195. string before the suffix must give m() > 0.
  196. """
  197. if self.b[self.k - 1] == "a":
  198. if self.ends("ational"):
  199. self.r("ate")
  200. elif self.ends("tional"):
  201. self.r("tion")
  202. elif self.b[self.k - 1] == "c":
  203. if self.ends("enci"):
  204. self.r("ence")
  205. elif self.ends("anci"):
  206. self.r("ance")
  207. elif self.b[self.k - 1] == "e":
  208. if self.ends("izer"):
  209. self.r("ize")
  210. elif self.b[self.k - 1] == "l":
  211. if self.ends("bli"):
  212. self.r("ble") # --DEPARTURE--
  213. # To match the published algorithm, replace this phrase with
  214. # if self.ends("abli"): self.r("able")
  215. elif self.ends("alli"):
  216. self.r("al")
  217. elif self.ends("entli"):
  218. self.r("ent")
  219. elif self.ends("eli"):
  220. self.r("e")
  221. elif self.ends("ousli"):
  222. self.r("ous")
  223. elif self.b[self.k - 1] == "o":
  224. if self.ends("ization"):
  225. self.r("ize")
  226. elif self.ends("ation"):
  227. self.r("ate")
  228. elif self.ends("ator"):
  229. self.r("ate")
  230. elif self.b[self.k - 1] == "s":
  231. if self.ends("alism"):
  232. self.r("al")
  233. elif self.ends("iveness"):
  234. self.r("ive")
  235. elif self.ends("fulness"):
  236. self.r("ful")
  237. elif self.ends("ousness"):
  238. self.r("ous")
  239. elif self.b[self.k - 1] == "t":
  240. if self.ends("aliti"):
  241. self.r("al")
  242. elif self.ends("iviti"):
  243. self.r("ive")
  244. elif self.ends("biliti"):
  245. self.r("ble")
  246. elif self.b[self.k - 1] == "g": # --DEPARTURE--
  247. if self.ends("logi"):
  248. self.r("log")
  249. # To match the published algorithm, delete this phrase
  250. def step3(self):
  251. """step3() dels with -ic-, -full, -ness etc. similar strategy to step2."""
  252. if self.b[self.k] == "e":
  253. if self.ends("icate"):
  254. self.r("ic")
  255. elif self.ends("ative"):
  256. self.r("")
  257. elif self.ends("alize"):
  258. self.r("al")
  259. elif self.b[self.k] == "i":
  260. if self.ends("iciti"):
  261. self.r("ic")
  262. elif self.b[self.k] == "l":
  263. if self.ends("ical"):
  264. self.r("ic")
  265. elif self.ends("ful"):
  266. self.r("")
  267. elif self.b[self.k] == "s":
  268. if self.ends("ness"):
  269. self.r("")
  270. def step4(self):
  271. """step4() takes off -ant, -ence etc., in context <c>vcvc<v>."""
  272. if self.b[self.k - 1] == "a":
  273. if self.ends("al"):
  274. pass
  275. else:
  276. return
  277. elif self.b[self.k - 1] == "c":
  278. if self.ends("ance"):
  279. pass
  280. elif self.ends("ence"):
  281. pass
  282. else:
  283. return
  284. elif self.b[self.k - 1] == "e":
  285. if self.ends("er"):
  286. pass
  287. else:
  288. return
  289. elif self.b[self.k - 1] == "i":
  290. if self.ends("ic"):
  291. pass
  292. else:
  293. return
  294. elif self.b[self.k - 1] == "l":
  295. if self.ends("able"):
  296. pass
  297. elif self.ends("ible"):
  298. pass
  299. else:
  300. return
  301. elif self.b[self.k - 1] == "n":
  302. if self.ends("ant"):
  303. pass
  304. elif self.ends("ement"):
  305. pass
  306. elif self.ends("ment"):
  307. pass
  308. elif self.ends("ent"):
  309. pass
  310. else:
  311. return
  312. elif self.b[self.k - 1] == "o":
  313. if self.ends("ion") and (self.b[self.j] == "s" or self.b[self.j] == "t"):
  314. pass
  315. elif self.ends("ou"):
  316. pass
  317. # takes care of -ous
  318. else:
  319. return
  320. elif self.b[self.k - 1] == "s":
  321. if self.ends("ism"):
  322. pass
  323. else:
  324. return
  325. elif self.b[self.k - 1] == "t":
  326. if self.ends("ate"):
  327. pass
  328. elif self.ends("iti"):
  329. pass
  330. else:
  331. return
  332. elif self.b[self.k - 1] == "u":
  333. if self.ends("ous"):
  334. pass
  335. else:
  336. return
  337. elif self.b[self.k - 1] == "v":
  338. if self.ends("ive"):
  339. pass
  340. else:
  341. return
  342. elif self.b[self.k - 1] == "z":
  343. if self.ends("ize"):
  344. pass
  345. else:
  346. return
  347. else:
  348. return
  349. if self.m() > 1:
  350. self.k = self.j
  351. def step5(self):
  352. """step5() removes a final -e if m() > 1, and changes -ll to -l if
  353. m() > 1.
  354. """
  355. self.j = self.k
  356. if self.b[self.k] == "e":
  357. a = self.m()
  358. if a > 1 or (a == 1 and not self.cvc(self.k - 1)):
  359. self.k = self.k - 1
  360. if self.b[self.k] == "l" and self.doublec(self.k) and self.m() > 1:
  361. self.k = self.k - 1
  362. def stem(self, p, metadata=None):
  363. """In stem(p,i,j), p is a char pointer, and the string to be stemmed
  364. is from p[i] to p[j] inclusive. Typically i is zero and j is the
  365. offset to the last character of a string, (p[j+1] == '\0'). The
  366. stemmer adjusts the characters p[i] ... p[j] and returns the new
  367. end-point of the string, k. Stemming never increases word length, so
  368. i <= k <= j. To turn the stemmer into a module, declare 'stem' as
  369. extern, and delete the remainder of this file.
  370. """
  371. # TODO: removed i and j from the original implementation
  372. # to comply with the `token.update` API
  373. i = 0
  374. j = len(p) - 1
  375. # copy the parameters into statics
  376. self.b = p
  377. self.k = j
  378. self.k0 = i
  379. if self.k <= self.k0 + 1:
  380. return self.b # --DEPARTURE--
  381. # With this line, strings of length 1 or 2 don't go through the
  382. # stemming process, although no mention is made of this in the
  383. # published algorithm. Remove the line to match the published
  384. # algorithm.
  385. self.step1ab()
  386. self.step1c()
  387. self.step2()
  388. self.step3()
  389. self.step4()
  390. self.step5()
  391. return self.b[self.k0 : self.k + 1]
  392. porter_stemmer = PorterStemmer()
  393. def stemmer(token, i=None, tokens=None):
  394. """Wrapper around the PorterStemmer for inclusion in pipeline.
  395. Args:
  396. language (str): ISO-639-1 code of the language.
  397. token (lunr.Token): The token to stem.
  398. i (int): The index of the token in a set.
  399. tokens (list): A list of tokens representing the set.
  400. """
  401. return token.update(porter_stemmer.stem)
  402. Pipeline.register_function(stemmer, "stemmer")