PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/analysis/common/src/java/org/apache/lucene/analysis/en/PorterStemmer.java

https://github.com/simplegeo/lucene-solr
Java | 547 lines | 339 code | 54 blank | 154 comment | 146 complexity | b908c4016bac422432ff6d8faa147ec5 MD5 | raw file
  1. package org.apache.lucene.analysis.en;
  2. /**
  3. * Licensed to the Apache Software Foundation (ASF) under one or more
  4. * contributor license agreements. See the NOTICE file distributed with
  5. * this work for additional information regarding copyright ownership.
  6. * The ASF licenses this file to You under the Apache License, Version 2.0
  7. * (the "License"); you may not use this file except in compliance with
  8. * the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. /*
  19. Porter stemmer in Java. The original paper is in
  20. Porter, 1980, An algorithm for suffix stripping, Program, Vol. 14,
  21. no. 3, pp 130-137,
  22. See also http://www.tartarus.org/~martin/PorterStemmer/index.html
  23. Bug 1 (reported by Gonzalo Parra 16/10/99) fixed as marked below.
  24. Tthe words 'aed', 'eed', 'oed' leave k at 'a' for step 3, and b[k-1]
  25. is then out outside the bounds of b.
  26. Similarly,
  27. Bug 2 (reported by Steve Dyrdahl 22/2/00) fixed as marked below.
  28. 'ion' by itself leaves j = -1 in the test for 'ion' in step 5, and
  29. b[j] is then outside the bounds of b.
  30. Release 3.
  31. [ This version is derived from Release 3, modified by Brian Goetz to
  32. optimize for fewer object creations. ]
  33. */
  34. import java.io.IOException;
  35. import java.io.InputStream;
  36. import java.io.FileInputStream;
  37. import static org.apache.lucene.util.RamUsageEstimator.NUM_BYTES_CHAR;
  38. import org.apache.lucene.util.ArrayUtil;
  39. /**
  40. *
  41. * Stemmer, implementing the Porter Stemming Algorithm
  42. *
  43. * The Stemmer class transforms a word into its root form. The input
  44. * word can be provided a character at time (by calling add()), or at once
  45. * by calling one of the various stem(something) methods.
  46. */
  47. class PorterStemmer
  48. {
  49. private char[] b;
  50. private int i, /* offset into b */
  51. j, k, k0;
  52. private boolean dirty = false;
  53. private static final int INITIAL_SIZE = 50;
  54. public PorterStemmer() {
  55. b = new char[INITIAL_SIZE];
  56. i = 0;
  57. }
  58. /**
  59. * reset() resets the stemmer so it can stem another word. If you invoke
  60. * the stemmer by calling add(char) and then stem(), you must call reset()
  61. * before starting another word.
  62. */
  63. public void reset() { i = 0; dirty = false; }
  64. /**
  65. * Add a character to the word being stemmed. When you are finished
  66. * adding characters, you can call stem(void) to process the word.
  67. */
  68. public void add(char ch) {
  69. if (b.length <= i) {
  70. b = ArrayUtil.grow(b, i+1);
  71. }
  72. b[i++] = ch;
  73. }
  74. /**
  75. * After a word has been stemmed, it can be retrieved by toString(),
  76. * or a reference to the internal buffer can be retrieved by getResultBuffer
  77. * and getResultLength (which is generally more efficient.)
  78. */
  79. @Override
  80. public String toString() { return new String(b,0,i); }
  81. /**
  82. * Returns the length of the word resulting from the stemming process.
  83. */
  84. public int getResultLength() { return i; }
  85. /**
  86. * Returns a reference to a character buffer containing the results of
  87. * the stemming process. You also need to consult getResultLength()
  88. * to determine the length of the result.
  89. */
  90. public char[] getResultBuffer() { return b; }
  91. /* cons(i) is true <=> b[i] is a consonant. */
  92. private final boolean cons(int i) {
  93. switch (b[i]) {
  94. case 'a': case 'e': case 'i': case 'o': case 'u':
  95. return false;
  96. case 'y':
  97. return (i==k0) ? true : !cons(i-1);
  98. default:
  99. return true;
  100. }
  101. }
  102. /* m() measures the number of consonant sequences between k0 and j. if c is
  103. a consonant sequence and v a vowel sequence, and <..> indicates arbitrary
  104. presence,
  105. <c><v> gives 0
  106. <c>vc<v> gives 1
  107. <c>vcvc<v> gives 2
  108. <c>vcvcvc<v> gives 3
  109. ....
  110. */
  111. private final int m() {
  112. int n = 0;
  113. int i = k0;
  114. while(true) {
  115. if (i > j)
  116. return n;
  117. if (! cons(i))
  118. break;
  119. i++;
  120. }
  121. i++;
  122. while(true) {
  123. while(true) {
  124. if (i > j)
  125. return n;
  126. if (cons(i))
  127. break;
  128. i++;
  129. }
  130. i++;
  131. n++;
  132. while(true) {
  133. if (i > j)
  134. return n;
  135. if (! cons(i))
  136. break;
  137. i++;
  138. }
  139. i++;
  140. }
  141. }
  142. /* vowelinstem() is true <=> k0,...j contains a vowel */
  143. private final boolean vowelinstem() {
  144. int i;
  145. for (i = k0; i <= j; i++)
  146. if (! cons(i))
  147. return true;
  148. return false;
  149. }
  150. /* doublec(j) is true <=> j,(j-1) contain a double consonant. */
  151. private final boolean doublec(int j) {
  152. if (j < k0+1)
  153. return false;
  154. if (b[j] != b[j-1])
  155. return false;
  156. return cons(j);
  157. }
  158. /* cvc(i) is true <=> i-2,i-1,i has the form consonant - vowel - consonant
  159. and also if the second c is not w,x or y. this is used when trying to
  160. restore an e at the end of a short word. e.g.
  161. cav(e), lov(e), hop(e), crim(e), but
  162. snow, box, tray.
  163. */
  164. private final boolean cvc(int i) {
  165. if (i < k0+2 || !cons(i) || cons(i-1) || !cons(i-2))
  166. return false;
  167. else {
  168. int ch = b[i];
  169. if (ch == 'w' || ch == 'x' || ch == 'y') return false;
  170. }
  171. return true;
  172. }
  173. private final boolean ends(String s) {
  174. int l = s.length();
  175. int o = k-l+1;
  176. if (o < k0)
  177. return false;
  178. for (int i = 0; i < l; i++)
  179. if (b[o+i] != s.charAt(i))
  180. return false;
  181. j = k-l;
  182. return true;
  183. }
  184. /* setto(s) sets (j+1),...k to the characters in the string s, readjusting
  185. k. */
  186. void setto(String s) {
  187. int l = s.length();
  188. int o = j+1;
  189. for (int i = 0; i < l; i++)
  190. b[o+i] = s.charAt(i);
  191. k = j+l;
  192. dirty = true;
  193. }
  194. /* r(s) is used further down. */
  195. void r(String s) { if (m() > 0) setto(s); }
  196. /* step1() gets rid of plurals and -ed or -ing. e.g.
  197. caresses -> caress
  198. ponies -> poni
  199. ties -> ti
  200. caress -> caress
  201. cats -> cat
  202. feed -> feed
  203. agreed -> agree
  204. disabled -> disable
  205. matting -> mat
  206. mating -> mate
  207. meeting -> meet
  208. milling -> mill
  209. messing -> mess
  210. meetings -> meet
  211. */
  212. private final void step1() {
  213. if (b[k] == 's') {
  214. if (ends("sses")) k -= 2;
  215. else if (ends("ies")) setto("i");
  216. else if (b[k-1] != 's') k--;
  217. }
  218. if (ends("eed")) {
  219. if (m() > 0)
  220. k--;
  221. }
  222. else if ((ends("ed") || ends("ing")) && vowelinstem()) {
  223. k = j;
  224. if (ends("at")) setto("ate");
  225. else if (ends("bl")) setto("ble");
  226. else if (ends("iz")) setto("ize");
  227. else if (doublec(k)) {
  228. int ch = b[k--];
  229. if (ch == 'l' || ch == 's' || ch == 'z')
  230. k++;
  231. }
  232. else if (m() == 1 && cvc(k))
  233. setto("e");
  234. }
  235. }
  236. /* step2() turns terminal y to i when there is another vowel in the stem. */
  237. private final void step2() {
  238. if (ends("y") && vowelinstem()) {
  239. b[k] = 'i';
  240. dirty = true;
  241. }
  242. }
  243. /* step3() maps double suffices to single ones. so -ization ( = -ize plus
  244. -ation) maps to -ize etc. note that the string before the suffix must give
  245. m() > 0. */
  246. private final void step3() {
  247. if (k == k0) return; /* For Bug 1 */
  248. switch (b[k-1]) {
  249. case 'a':
  250. if (ends("ational")) { r("ate"); break; }
  251. if (ends("tional")) { r("tion"); break; }
  252. break;
  253. case 'c':
  254. if (ends("enci")) { r("ence"); break; }
  255. if (ends("anci")) { r("ance"); break; }
  256. break;
  257. case 'e':
  258. if (ends("izer")) { r("ize"); break; }
  259. break;
  260. case 'l':
  261. if (ends("bli")) { r("ble"); break; }
  262. if (ends("alli")) { r("al"); break; }
  263. if (ends("entli")) { r("ent"); break; }
  264. if (ends("eli")) { r("e"); break; }
  265. if (ends("ousli")) { r("ous"); break; }
  266. break;
  267. case 'o':
  268. if (ends("ization")) { r("ize"); break; }
  269. if (ends("ation")) { r("ate"); break; }
  270. if (ends("ator")) { r("ate"); break; }
  271. break;
  272. case 's':
  273. if (ends("alism")) { r("al"); break; }
  274. if (ends("iveness")) { r("ive"); break; }
  275. if (ends("fulness")) { r("ful"); break; }
  276. if (ends("ousness")) { r("ous"); break; }
  277. break;
  278. case 't':
  279. if (ends("aliti")) { r("al"); break; }
  280. if (ends("iviti")) { r("ive"); break; }
  281. if (ends("biliti")) { r("ble"); break; }
  282. break;
  283. case 'g':
  284. if (ends("logi")) { r("log"); break; }
  285. }
  286. }
  287. /* step4() deals with -ic-, -full, -ness etc. similar strategy to step3. */
  288. private final void step4() {
  289. switch (b[k]) {
  290. case 'e':
  291. if (ends("icate")) { r("ic"); break; }
  292. if (ends("ative")) { r(""); break; }
  293. if (ends("alize")) { r("al"); break; }
  294. break;
  295. case 'i':
  296. if (ends("iciti")) { r("ic"); break; }
  297. break;
  298. case 'l':
  299. if (ends("ical")) { r("ic"); break; }
  300. if (ends("ful")) { r(""); break; }
  301. break;
  302. case 's':
  303. if (ends("ness")) { r(""); break; }
  304. break;
  305. }
  306. }
  307. /* step5() takes off -ant, -ence etc., in context <c>vcvc<v>. */
  308. private final void step5() {
  309. if (k == k0) return; /* for Bug 1 */
  310. switch (b[k-1]) {
  311. case 'a':
  312. if (ends("al")) break;
  313. return;
  314. case 'c':
  315. if (ends("ance")) break;
  316. if (ends("ence")) break;
  317. return;
  318. case 'e':
  319. if (ends("er")) break; return;
  320. case 'i':
  321. if (ends("ic")) break; return;
  322. case 'l':
  323. if (ends("able")) break;
  324. if (ends("ible")) break; return;
  325. case 'n':
  326. if (ends("ant")) break;
  327. if (ends("ement")) break;
  328. if (ends("ment")) break;
  329. /* element etc. not stripped before the m */
  330. if (ends("ent")) break;
  331. return;
  332. case 'o':
  333. if (ends("ion") && j >= 0 && (b[j] == 's' || b[j] == 't')) break;
  334. /* j >= 0 fixes Bug 2 */
  335. if (ends("ou")) break;
  336. return;
  337. /* takes care of -ous */
  338. case 's':
  339. if (ends("ism")) break;
  340. return;
  341. case 't':
  342. if (ends("ate")) break;
  343. if (ends("iti")) break;
  344. return;
  345. case 'u':
  346. if (ends("ous")) break;
  347. return;
  348. case 'v':
  349. if (ends("ive")) break;
  350. return;
  351. case 'z':
  352. if (ends("ize")) break;
  353. return;
  354. default:
  355. return;
  356. }
  357. if (m() > 1)
  358. k = j;
  359. }
  360. /* step6() removes a final -e if m() > 1. */
  361. private final void step6() {
  362. j = k;
  363. if (b[k] == 'e') {
  364. int a = m();
  365. if (a > 1 || a == 1 && !cvc(k-1))
  366. k--;
  367. }
  368. if (b[k] == 'l' && doublec(k) && m() > 1)
  369. k--;
  370. }
  371. /**
  372. * Stem a word provided as a String. Returns the result as a String.
  373. */
  374. public String stem(String s) {
  375. if (stem(s.toCharArray(), s.length()))
  376. return toString();
  377. else
  378. return s;
  379. }
  380. /** Stem a word contained in a char[]. Returns true if the stemming process
  381. * resulted in a word different from the input. You can retrieve the
  382. * result with getResultLength()/getResultBuffer() or toString().
  383. */
  384. public boolean stem(char[] word) {
  385. return stem(word, word.length);
  386. }
  387. /** Stem a word contained in a portion of a char[] array. Returns
  388. * true if the stemming process resulted in a word different from
  389. * the input. You can retrieve the result with
  390. * getResultLength()/getResultBuffer() or toString().
  391. */
  392. public boolean stem(char[] wordBuffer, int offset, int wordLen) {
  393. reset();
  394. if (b.length < wordLen) {
  395. b = new char[ArrayUtil.oversize(wordLen, NUM_BYTES_CHAR)];
  396. }
  397. System.arraycopy(wordBuffer, offset, b, 0, wordLen);
  398. i = wordLen;
  399. return stem(0);
  400. }
  401. /** Stem a word contained in a leading portion of a char[] array.
  402. * Returns true if the stemming process resulted in a word different
  403. * from the input. You can retrieve the result with
  404. * getResultLength()/getResultBuffer() or toString().
  405. */
  406. public boolean stem(char[] word, int wordLen) {
  407. return stem(word, 0, wordLen);
  408. }
  409. /** Stem the word placed into the Stemmer buffer through calls to add().
  410. * Returns true if the stemming process resulted in a word different
  411. * from the input. You can retrieve the result with
  412. * getResultLength()/getResultBuffer() or toString().
  413. */
  414. public boolean stem() {
  415. return stem(0);
  416. }
  417. public boolean stem(int i0) {
  418. k = i - 1;
  419. k0 = i0;
  420. if (k > k0+1) {
  421. step1(); step2(); step3(); step4(); step5(); step6();
  422. }
  423. // Also, a word is considered dirty if we lopped off letters
  424. // Thanks to Ifigenia Vairelles for pointing this out.
  425. if (i != k+1)
  426. dirty = true;
  427. i = k+1;
  428. return dirty;
  429. }
  430. /** Test program for demonstrating the Stemmer. It reads a file and
  431. * stems each word, writing the result to standard out.
  432. * Usage: Stemmer file-name
  433. */
  434. public static void main(String[] args) {
  435. PorterStemmer s = new PorterStemmer();
  436. for (int i = 0; i < args.length; i++) {
  437. try {
  438. InputStream in = new FileInputStream(args[i]);
  439. byte[] buffer = new byte[1024];
  440. int bufferLen, offset, ch;
  441. bufferLen = in.read(buffer);
  442. offset = 0;
  443. s.reset();
  444. while(true) {
  445. if (offset < bufferLen)
  446. ch = buffer[offset++];
  447. else {
  448. bufferLen = in.read(buffer);
  449. offset = 0;
  450. if (bufferLen < 0)
  451. ch = -1;
  452. else
  453. ch = buffer[offset++];
  454. }
  455. if (Character.isLetter((char) ch)) {
  456. s.add(Character.toLowerCase((char) ch));
  457. }
  458. else {
  459. s.stem();
  460. System.out.print(s.toString());
  461. s.reset();
  462. if (ch < 0)
  463. break;
  464. else {
  465. System.out.print((char) ch);
  466. }
  467. }
  468. }
  469. in.close();
  470. }
  471. catch (IOException e) {
  472. System.out.println("error reading " + args[i]);
  473. }
  474. }
  475. }
  476. }