-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTermSegmentor.java
More file actions
84 lines (77 loc) · 2.95 KB
/
TermSegmentor.java
File metadata and controls
84 lines (77 loc) · 2.95 KB
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
import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.NlpAnalysis;
import org.ansj.splitWord.analysis.ToAnalysis;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.ArrayList;
// Overview:
// given a set of stop words,
// a instance of the word segmentor takes input of a list of strings,
// and for each string, produces output of a list of segmented terms
public class TermSegmentor {
// stop words
private Set<String> stopWords;
private static final String ENCODING = "UTF-8";
private static final String STOP_WORDS_PATH = ".\\data\\stopWords.txt";
public TermSegmentor(Set<String> stopWords) {
this.stopWords = new HashSet<String>(stopWords);
}
public TermSegmentor() {
try {
this.stopWords = new HashSet<>();
File stopWordsFile = new File(STOP_WORDS_PATH);
if (stopWordsFile.isFile() && stopWordsFile.exists()) {
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(stopWordsFile), ENCODING);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
stopWords.add(line);
}
this.stopWords.add("");
this.stopWords.add(" ");
this.stopWords.add("\r");
this.stopWords.add("\n");
this.stopWords.add("\r\n");
this.stopWords.add("nbsp");
this.stopWords.add("\u0000");
bufferedReader.close();
}
} catch (Exception e) {
System.out.println("failed to read stop words");
}
}
private List<String> filterStopWords(List<String> words) {
List<String> filteredWords = new ArrayList<>();
for (String word : words) {
if (!stopWords.contains(word)) {
filteredWords.add(word);
}
}
return filteredWords;
}
public List<String> segmentSentence(String sentence) {
List<String> terms = new ArrayList<>();
try {
List<Term> tokens = NlpAnalysis.parse(sentence).getTerms();
for (Term term : tokens) {
terms.add(term.getName());
}
} catch (Exception e) {
System.out.println("segment failure");
}
return filterStopWords(terms);
}
public List<List<String>> segmentSentences(List<String> sentences) {
List<List<String>> termsList = new ArrayList<>();
for (String sentence : sentences) {
List<String> terms = segmentSentence(sentence);
termsList.add(terms);
}
return termsList;
}
}