add --shared
[pylucene.git] / lucene-java-3.4.0 / lucene / contrib / analyzers / smartcn / src / java / org / apache / lucene / analysis / cn / smart / SmartChineseAnalyzer.java
1 /**
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements.  See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License.  You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 package org.apache.lucene.analysis.cn.smart;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.InputStreamReader;
23 import java.io.Reader;
24 import java.util.Collections;
25 import java.util.Set;
26
27 import org.apache.lucene.analysis.Analyzer;
28 import org.apache.lucene.analysis.PorterStemFilter;
29 import org.apache.lucene.analysis.StopFilter;
30 import org.apache.lucene.analysis.TokenStream;
31 import org.apache.lucene.analysis.Tokenizer;
32 import org.apache.lucene.analysis.WordlistLoader;
33 import org.apache.lucene.analysis.cn.smart.SentenceTokenizer;
34 import org.apache.lucene.analysis.cn.smart.WordTokenFilter;
35 import org.apache.lucene.util.Version;
36
37 /**
38  * <p>
39  * SmartChineseAnalyzer is an analyzer for Chinese or mixed Chinese-English text.
40  * The analyzer uses probabilistic knowledge to find the optimal word segmentation for Simplified Chinese text.
41  * The text is first broken into sentences, then each sentence is segmented into words.
42  * </p>
43  * <p>
44  * Segmentation is based upon the <a href="http://en.wikipedia.org/wiki/Hidden_Markov_Model">Hidden Markov Model</a>. 
45  * A large training corpus was used to calculate Chinese word frequency probability.
46  * </p>
47  * <p>
48  * This analyzer requires a dictionary to provide statistical data. 
49  * SmartChineseAnalyzer has an included dictionary out-of-box.
50  * </p>
51  * <p>
52  * The included dictionary data is from <a href="http://www.ictclas.org">ICTCLAS1.0</a>.
53  * Thanks to ICTCLAS for their hard work, and for contributing the data under the Apache 2 License!
54  * </p>
55  * @lucene.experimental
56  */
57 public final class SmartChineseAnalyzer extends Analyzer {
58
59   private final Set<?> stopWords;
60   
61   private static final String DEFAULT_STOPWORD_FILE = "stopwords.txt";
62   
63   private static final String STOPWORD_FILE_COMMENT = "//";
64   
65   /**
66    * Returns an unmodifiable instance of the default stop-words set.
67    * @return an unmodifiable instance of the default stop-words set.
68    */
69   public static Set<String> getDefaultStopSet(){
70     return DefaultSetHolder.DEFAULT_STOP_SET;
71   }
72   
73   /**
74    * Atomically loads the DEFAULT_STOP_SET in a lazy fashion once the outer class 
75    * accesses the static final set the first time.;
76    */
77   private static class DefaultSetHolder {
78     static final Set<String> DEFAULT_STOP_SET;
79
80     static {
81       try {
82         DEFAULT_STOP_SET = loadDefaultStopWordSet();
83       } catch (IOException ex) {
84         // default set should always be present as it is part of the
85         // distribution (JAR)
86         throw new RuntimeException("Unable to load default stopword set");
87       }
88     }
89
90     static Set<String> loadDefaultStopWordSet() throws IOException {
91       InputStream stream = SmartChineseAnalyzer.class
92           .getResourceAsStream(DEFAULT_STOPWORD_FILE);
93       try {
94         InputStreamReader reader = new InputStreamReader(stream, "UTF-8");
95         // make sure it is unmodifiable as we expose it in the outer class
96         return Collections.unmodifiableSet(WordlistLoader.getWordSet(reader, STOPWORD_FILE_COMMENT));
97       } finally {
98         stream.close();
99       }
100     }
101   }
102
103   private final Version matchVersion;
104
105   /**
106    * Create a new SmartChineseAnalyzer, using the default stopword list.
107    */
108   public SmartChineseAnalyzer(Version matchVersion) {
109     this(matchVersion, true);
110   }
111
112   /**
113    * <p>
114    * Create a new SmartChineseAnalyzer, optionally using the default stopword list.
115    * </p>
116    * <p>
117    * The included default stopword list is simply a list of punctuation.
118    * If you do not use this list, punctuation will not be removed from the text!
119    * </p>
120    * 
121    * @param useDefaultStopWords true to use the default stopword list.
122    */
123   public SmartChineseAnalyzer(Version matchVersion, boolean useDefaultStopWords) {
124     stopWords = useDefaultStopWords ? DefaultSetHolder.DEFAULT_STOP_SET
125       : Collections.EMPTY_SET;
126     this.matchVersion = matchVersion;
127   }
128
129   /**
130    * <p>
131    * Create a new SmartChineseAnalyzer, using the provided {@link Set} of stopwords.
132    * </p>
133    * <p>
134    * Note: the set should include punctuation, unless you want to index punctuation!
135    * </p>
136    * @param stopWords {@link Set} of stopwords to use.
137    */
138   public SmartChineseAnalyzer(Version matchVersion, Set stopWords) {
139     this.stopWords = stopWords==null?Collections.EMPTY_SET:stopWords;
140     this.matchVersion = matchVersion;
141   }
142
143   @Override
144   public TokenStream tokenStream(String fieldName, Reader reader) {
145     TokenStream result = new SentenceTokenizer(reader);
146     result = new WordTokenFilter(result);
147     // result = new LowerCaseFilter(result);
148     // LowerCaseFilter is not needed, as SegTokenFilter lowercases Basic Latin text.
149     // The porter stemming is too strict, this is not a bug, this is a feature:)
150     result = new PorterStemFilter(result);
151     if (!stopWords.isEmpty()) {
152       result = new StopFilter(matchVersion, result, stopWords, false);
153     }
154     return result;
155   }
156   
157   private static final class SavedStreams {
158     Tokenizer tokenStream;
159     TokenStream filteredTokenStream;
160   }
161   
162   @Override
163   public TokenStream reusableTokenStream(String fieldName, Reader reader)
164       throws IOException {
165     SavedStreams streams = (SavedStreams) getPreviousTokenStream();
166     if (streams == null) {
167       streams = new SavedStreams();
168       setPreviousTokenStream(streams);
169       streams.tokenStream = new SentenceTokenizer(reader);
170       streams.filteredTokenStream = new WordTokenFilter(streams.tokenStream);
171       streams.filteredTokenStream = new PorterStemFilter(streams.filteredTokenStream);
172       if (!stopWords.isEmpty()) {
173         streams.filteredTokenStream = new StopFilter(matchVersion, streams.filteredTokenStream, stopWords, false);
174       }
175     } else {
176       streams.tokenStream.reset(reader);
177       streams.filteredTokenStream.reset(); // reset WordTokenFilter's state
178     }
179
180     return streams.filteredTokenStream;
181   }
182 }