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