]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/SingleDictFileParser.java~
Enable single-language dictionary
[DictionaryPC.git] / src / com / hughes / android / dictionary / parser / SingleDictFileParser.java~
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 //     http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12
13 package com.hughes.android.dictionary.parser;
14
15 import java.io.BufferedReader;
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.nio.charset.Charset;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.LinkedHashSet;
24 import java.util.Set;
25 import java.util.logging.Logger;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
28
29 import com.hughes.android.dictionary.engine.DictionaryBuilder;
30 import com.hughes.android.dictionary.engine.EntrySource;
31 import com.hughes.android.dictionary.engine.EntryTypeName;
32 import com.hughes.android.dictionary.engine.HtmlEntry;
33 import com.hughes.android.dictionary.engine.IndexBuilder;
34 import com.hughes.android.dictionary.engine.IndexBuilder.TokenData;
35 import com.hughes.android.dictionary.engine.IndexedEntry;
36 import com.hughes.android.dictionary.engine.Language;
37 import com.hughes.android.dictionary.engine.PairEntry;
38 import com.hughes.util.StringUtil;
39
40 public class SingleDictFileParser implements Parser {
41
42     static final Logger logger = Logger.getLogger(SingleDictFileParser.class.getName());
43
44     // Dictcc
45     public static final String TAB = "\t";
46
47     // Chemnitz
48     public static final String DOUBLE_COLON = " :: ";
49     public static final String PIPE = "|";
50
51     static final Pattern SPACES = Pattern.compile("\\s+");
52
53     static final Pattern CURLY_BRACED = Pattern.compile("\\{([^}]+)\\}");
54
55     // http://www.regular-expressions.info/unicode.html
56     static final Pattern NON_CHAR_DASH = Pattern.compile("[^-'\\p{L}\\p{M}\\p{N}]+");
57     public static final Pattern NON_CHAR = Pattern.compile("[^\\p{L}\\p{M}\\p{N}]+");
58
59     static final Pattern TRIM_PUNC = Pattern.compile("^[^\\p{L}\\p{M}\\p{N}]+|[^\\p{L}\\p{M}\\p{N}]+$");
60
61     final Charset charset;
62
63     final String fieldSplit;
64
65     final DictionaryBuilder dictBuilder;
66
67     EntrySource entrySource;
68
69     // final Set<String> alreadyDone = new HashSet<String>();
70
71     public SingleDictFileParser(final Charset charset,
72                                 final String fieldSplit,
73                                 final DictionaryBuilder dictBuilder) {
74         this.charset = charset;
75         this.fieldSplit = fieldSplit;
76         this.dictBuilder = dictBuilder;
77     }
78
79     @Override
80     public void parse(final File file, final EntrySource entrySouce, final int pageLimit) throws IOException {
81         this.entrySource = entrySouce;
82         final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
83         String line;
84         int count = 0;
85         while ((line = reader.readLine()) != null) {
86             if (pageLimit >= 0 && count >= pageLimit) {
87                 return;
88             }
89             if (count % 10000 == 0) {
90                 logger.info("count=" + count + ", line=" + line);
91             }
92             parseLine(line);
93             ++count;
94         }
95     }
96
97     private void parseLine(final String line) {
98         if (line.startsWith("#") || line.isEmpty()) {
99             logger.info("Skipping comment line: " + line);
100             return;
101         }
102         final String[] fields = StringUtil.split(line, fieldSplit);
103         if (fields.length < 2 || fields.length > 4) {
104             logger.warning("Malformed line, expected 3 or 4 fields, got " + fields.length + ": " + line);
105             return;
106         }
107
108         String headword = SPACES.matcher(fields[0]).replaceAll(" ").trim();
109         String definition = SPACES.matcher(fields[1]).replaceAll(" ").trim();
110
111         final HtmlEntry htmlEntry = new HtmlEntry(entrySource, headword);
112         htmlEntry.html = definition;
113         IndexedEntry entryData = new IndexedEntry(htmlEntry);
114         entryData.isValid = true;
115
116         final IndexBuilder titleIndexBuilder = dictBuilder.indexBuilders.get(0);
117         final TokenData tokenData = titleIndexBuilder.getOrCreateTokenData(headword);
118         tokenData.hasMainEntry = true;
119
120         htmlEntry.addToDictionary(titleIndexBuilder.index.dict);
121         tokenData.htmlEntries.add(htmlEntry);
122         
123         entryData = null;
124     }
125
126     private StringBuilder extractParenthesized(StringBuilder in, String startChar, String endChar) {
127         StringBuilder res = new StringBuilder();
128         int pos = 0;
129         while ((pos = in.indexOf(startChar, pos)) != -1) {
130             int end = in.indexOf(endChar, pos + 1);
131             if (end == -1) break;
132             res.append(in, pos + 1, end).append(" ");
133             in.replace(pos, end + 1, " ");
134             pos++; // skip the just appended space
135         }
136         return res;
137     }
138
139     private void parseFieldGeneric(final IndexBuilder indexBuilder, String field,
140                                    final IndexedEntry entryData, final int subfieldIdx, final int numSubFields) {
141         final StringBuilder fieldsb = new StringBuilder(field);
142         // remove bracketed and parenthesized stuff.
143         final StringBuilder bracketed = extractParenthesized(fieldsb, "[", "]");
144         final StringBuilder parenthesized = extractParenthesized(fieldsb, "(", ")");
145
146         field = fieldsb.toString().trim();
147
148         // split words on non -A-z0-9, do them.
149         final String[] tokens = NON_CHAR_DASH.split(field);
150
151         final EntryTypeName entryTypeName;
152         if (numSubFields == 1) {
153             assert subfieldIdx == 0;
154             if (tokens.length == 1) {
155                 entryTypeName = EntryTypeName.ONE_WORD;
156             } else if (tokens.length == 2) {
157                 entryTypeName = EntryTypeName.TWO_WORDS;
158             } else if (tokens.length == 3) {
159                 entryTypeName = EntryTypeName.THREE_WORDS;
160             } else if (tokens.length == 4) {
161                 entryTypeName = EntryTypeName.FOUR_WORDS;
162             } else {
163                 entryTypeName = EntryTypeName.FIVE_OR_MORE_WORDS;
164             }
165         } else {
166             assert numSubFields > 1;
167             if (subfieldIdx == 0) {
168                 if (tokens.length == 1) {
169                     entryTypeName = EntryTypeName.MULTIROW_HEAD_ONE_WORD;
170                 } else {
171                     entryTypeName = EntryTypeName.MULTIROW_HEAD_MANY_WORDS;
172                 }
173             } else {
174                 assert subfieldIdx > 0;
175                 if (tokens.length == 1) {
176                     entryTypeName = EntryTypeName.MULTIROW_TAIL_ONE_WORD;
177                 } else {
178                     entryTypeName = EntryTypeName.MULTIROW_TAIL_MANY_WORDS;
179                 }
180             }
181         }
182
183         for (String token : tokens) {
184             token = TRIM_PUNC.matcher(token).replaceAll("");
185             if (/*!alreadyDone.contains(token) && */!token.isEmpty()) {
186                 indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), entryTypeName);
187                 // alreadyDone.add(token);
188
189                 // also split words on dashes, do them, too.
190                 if (token.indexOf('-') != -1) {
191                     final String[] dashed = StringUtil.split(token, "-");
192                     for (final String dashedToken : dashed) {
193                         if (/*!alreadyDone.contains(dashedToken) && */!dashedToken.isEmpty()) {
194                             indexBuilder.addEntryWithTokens(entryData, Collections.singleton(dashedToken), EntryTypeName.PART_OF_HYPHENATED);
195                         }
196                     }
197                 }
198
199             }  // if (!alreadyDone.contains(token)) {
200         }  // for (final String token : tokens) {
201     }
202
203     public static Set<String> tokenize(final String text, final Pattern pattern) {
204         final String[] split = pattern.split(text);
205         final Set<String> result = new LinkedHashSet<>(Arrays.asList(split));
206         result.remove("");
207         return result;
208     }
209
210
211 }