]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/DictFileParser.java
f825ac56bdea456e961b0c5c370ac1e34f1bafa4
[DictionaryPC.git] / src / com / hughes / android / dictionary / parser / DictFileParser.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary.parser;
16
17 import java.io.BufferedReader;
18 import java.io.File;
19 import java.io.FileInputStream;
20 import java.io.IOException;
21 import java.io.InputStreamReader;
22 import java.nio.charset.Charset;
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.LinkedHashSet;
26 import java.util.Set;
27 import java.util.logging.Logger;
28 import java.util.regex.Matcher;
29 import java.util.regex.Pattern;
30
31 import com.hughes.android.dictionary.engine.DictionaryBuilder;
32 import com.hughes.android.dictionary.engine.EntrySource;
33 import com.hughes.android.dictionary.engine.EntryTypeName;
34 import com.hughes.android.dictionary.engine.IndexBuilder;
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
39 public class DictFileParser implements Parser {
40
41     static final Logger logger = Logger.getLogger(DictFileParser.class.getName());
42
43     // Dictcc
44     public static final Pattern TAB = Pattern.compile("\\t");
45
46     // Chemnitz
47     public static final Pattern DOUBLE_COLON = Pattern.compile(" :: ");
48     public static final Pattern PIPE = Pattern.compile("\\|");
49
50     static final Pattern SPACES = Pattern.compile("\\s+");
51
52     static final Pattern BRACKETED = Pattern.compile("\\[([^]]+)\\]");
53     static final Pattern PARENTHESIZED = Pattern.compile("\\(([^)]+)\\)");
54     static final Pattern CURLY_BRACED = Pattern.compile("\\{([^}]+)\\}");
55
56     // http://www.regular-expressions.info/unicode.html
57     static final Pattern NON_CHAR_DASH = Pattern.compile("[^-'\\p{L}\\p{M}\\p{N}]+");
58     public static final Pattern NON_CHAR = Pattern.compile("[^\\p{L}\\p{M}\\p{N}]+");
59
60     static final Pattern TRIM_PUNC = Pattern.compile("^[^\\p{L}\\p{M}\\p{N}]+|[^\\p{L}\\p{M}\\p{N}]+$");
61
62     final Charset charset;
63     final boolean flipCols;
64
65     final Pattern fieldSplit;
66     final Pattern subfieldSplit;
67
68     final DictionaryBuilder dictBuilder;
69
70     EntrySource entrySource;
71
72     // final Set<String> alreadyDone = new HashSet<String>();
73
74     public DictFileParser(final Charset charset, boolean flipCols,
75                           final Pattern fieldSplit, final Pattern subfieldSplit,
76                           final DictionaryBuilder dictBuilder) {
77         this.charset = charset;
78         this.flipCols = flipCols;
79         this.fieldSplit = fieldSplit;
80         this.subfieldSplit = subfieldSplit;
81         this.dictBuilder = dictBuilder;
82     }
83
84     @Override
85     public void parse(final File file, final EntrySource entrySouce, final int pageLimit) throws IOException {
86         this.entrySource = entrySouce;
87         final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
88         String line;
89         int count = 0;
90         while ((line = reader.readLine()) != null) {
91             if (pageLimit >= 0 && count >= pageLimit) {
92                 return;
93             }
94             if (count % 10000 == 0) {
95                 logger.info("count=" + count + ", line=" + line);
96             }
97             parseLine(line);
98             ++count;
99         }
100     }
101
102     private void parseLine(final String line) {
103         if (line.startsWith("#") || line.length() == 0) {
104             logger.info("Skipping comment line: " + line);
105             return;
106         }
107         final String[] fields = fieldSplit.split(line);
108         if (fields.length < 2 || fields.length > 4) {
109             logger.warning("Malformed line, expected 3 or 4 fields, got " + fields.length + ": " + line);
110             return;
111         }
112
113         fields[0] = SPACES.matcher(fields[0]).replaceAll(" ").trim();
114         fields[1] = SPACES.matcher(fields[1]).replaceAll(" ").trim();
115         if (flipCols) {
116             final String temp = fields[0];
117             fields[0] = fields[1];
118             fields[1] = temp;
119         }
120
121         final String[][] subfields = new String[2][];
122         if (subfieldSplit != null) {
123             subfields[0] = subfieldSplit.split(fields[0]);
124             subfields[1] = subfieldSplit.split(fields[1]);
125             if (subfields[0].length != subfields[1].length) {
126                 logger.warning("Number of subfields doesn't match: " + line);
127                 return;
128             }
129         } else {
130             subfields[0] = new String[] { fields[0] };
131             subfields[1] = new String[] { fields[1] };
132         }
133
134         final PairEntry pairEntry = new PairEntry(entrySource);
135         for (int i = 0; i < subfields[0].length; ++i) {
136             subfields[0][i] = subfields[0][i].trim();
137             subfields[1][i] = subfields[1][i].trim();
138             if (subfields[0][i].length() == 0 && subfields[1][i].length() == 0) {
139                 logger.warning("Empty pair: " + line);
140                 continue;
141             }
142             if (subfields[0][i].length() == 0) {
143                 subfields[0][i] = "__";
144             }
145             if (subfields[1][i].length() == 0) {
146                 subfields[1][i] = "__";
147             }
148             pairEntry.pairs.add(new PairEntry.Pair(subfields[0][i], subfields[1][i]));
149         }
150         final IndexedEntry entryData = new IndexedEntry(pairEntry);
151         entryData.isValid = true;
152
153         for (int l = 0; l < 2; ++l) {
154             // alreadyDone.clear();
155
156             final IndexBuilder indexBuilder = dictBuilder.indexBuilders.get(l);
157             for (int j = 0; j < subfields[l].length; ++j) {
158                 String subfield = subfields[l][j];
159                 if (indexBuilder.index.sortLanguage == Language.de) {
160                     subfield = parseField_DE(indexBuilder, subfield, entryData, j);
161                 } else if (indexBuilder.index.sortLanguage == Language.en) {
162                     subfield = parseField_EN(indexBuilder, subfield, entryData, j);
163                 }
164                 parseFieldGeneric(indexBuilder, subfield, entryData, j, subfields[l].length);
165             }
166         }
167     }
168
169     private void parseFieldGeneric(final IndexBuilder indexBuilder, String field,
170                                    final IndexedEntry entryData, final int subfieldIdx, final int numSubFields) {
171         // remove bracketed and parenthesized stuff.
172         final StringBuilder bracketed = new StringBuilder();
173         final StringBuilder parenthesized = new StringBuilder();
174
175         Matcher matcher;
176         while ((matcher = BRACKETED.matcher(field)).find()) {
177             bracketed.append(matcher.group(1)).append(" ");
178             field = matcher.replaceFirst(" ");
179         }
180
181         while ((matcher = PARENTHESIZED.matcher(field)).find()) {
182             parenthesized.append(matcher.group(1)).append(" ");
183             field = matcher.replaceFirst(" ");
184         }
185
186         field = SPACES.matcher(field).replaceAll(" ").trim();
187
188         // split words on non -A-z0-9, do them.
189         final String[] tokens = NON_CHAR_DASH.split(field);
190
191         final EntryTypeName entryTypeName;
192         if (numSubFields == 1) {
193             assert subfieldIdx == 0;
194             if (tokens.length == 1) {
195                 entryTypeName = EntryTypeName.ONE_WORD;
196             } else if (tokens.length == 2) {
197                 entryTypeName = EntryTypeName.TWO_WORDS;
198             } else if (tokens.length == 3) {
199                 entryTypeName = EntryTypeName.THREE_WORDS;
200             } else if (tokens.length == 4) {
201                 entryTypeName = EntryTypeName.FOUR_WORDS;
202             } else {
203                 entryTypeName = EntryTypeName.FIVE_OR_MORE_WORDS;
204             }
205         } else {
206             assert numSubFields > 1;
207             if (subfieldIdx == 0) {
208                 if (tokens.length == 1) {
209                     entryTypeName = EntryTypeName.MULTIROW_HEAD_ONE_WORD;
210                 } else {
211                     entryTypeName = EntryTypeName.MULTIROW_HEAD_MANY_WORDS;
212                 }
213             } else {
214                 assert subfieldIdx > 0;
215                 if (tokens.length == 1) {
216                     entryTypeName = EntryTypeName.MULTIROW_TAIL_ONE_WORD;
217                 } else {
218                     entryTypeName = EntryTypeName.MULTIROW_TAIL_MANY_WORDS;
219                 }
220             }
221         }
222
223         for (String token : tokens) {
224             token = TRIM_PUNC.matcher(token).replaceAll("");
225             if (/*!alreadyDone.contains(token) && */token.length() > 0) {
226                 indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), entryTypeName);
227                 // alreadyDone.add(token);
228
229                 // also split words on dashes, do them, too.
230                 if (token.contains("-")) {
231                     final String[] dashed = token.split("-");
232                     for (final String dashedToken : dashed) {
233                         if (/*!alreadyDone.contains(dashedToken) && */dashedToken.length() > 0) {
234                             indexBuilder.addEntryWithTokens(entryData, Collections.singleton(dashedToken), EntryTypeName.PART_OF_HYPHENATED);
235                         }
236                     }
237                 }
238
239             }  // if (!alreadyDone.contains(token)) {
240         }  // for (final String token : tokens) {
241
242         // process bracketed stuff (split on spaces and dashes always)
243         final String[] bracketedTokens = NON_CHAR.split(bracketed.toString());
244         for (final String token : bracketedTokens) {
245             assert !token.contains("-");
246             if (/*!alreadyDone.contains(token) && */token.length() > 0) {
247                 indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), EntryTypeName.BRACKETED);
248             }
249         }
250
251         // process paren stuff
252         final String[] parenTokens = NON_CHAR.split(parenthesized.toString());
253         for (final String token : parenTokens) {
254             assert !token.contains("-");
255             if (/*!alreadyDone.contains(token) && */token.length() > 0) {
256                 indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), EntryTypeName.PARENTHESIZED);
257             }
258         }
259
260     }
261
262     private String parseField_DE(final IndexBuilder indexBuilder, String field,
263                                  final IndexedEntry entryData, final int subfieldIdx) {
264
265 //    final Matcher matcher = DE_NOUN.matcher(field);
266 //    while (matcher.find()) {
267 //      final String noun = matcher.group(1);
268         //final String gender = matcher.group(2);
269 //      if (alreadyDone.add(noun)) {
270         // System.out.println("Found DE noun " + noun + ", " + gender);
271 //        final List<EntryData> entries = indexBuilder.getOrCreateEntries(noun, EntryTypeName.NOUN);
272 //        entries.add(entryData);
273 //      }
274 //    }
275
276         // In English, curly braces are used for different tenses.
277         field = CURLY_BRACED.matcher(field).replaceAll(" ");
278
279         return field;
280     }
281
282     private String parseField_EN(final IndexBuilder indexBuilder, String field,
283                                  final IndexedEntry entryData, final int subfieldIdx) {
284         if (field.startsWith("to ")) {
285             field = field.substring(3);
286         }
287         return field;
288     }
289
290     public static Set<String> tokenize(final String text, final Pattern pattern) {
291         final String[] split = pattern.split(text);
292         final Set<String> result = new LinkedHashSet<>(Arrays.asList(split));
293         result.remove("");
294         return result;
295     }
296
297
298 }