]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/DictFileParser.java
Move test data, fix DictFileParser, fix splitter, fix crash during
[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.IndexedEntry;
34 import com.hughes.android.dictionary.engine.EntryTypeName;
35 import com.hughes.android.dictionary.engine.IndexBuilder;
36 import com.hughes.android.dictionary.engine.Language;
37 import com.hughes.android.dictionary.engine.PairEntry;
38 import com.hughes.android.dictionary.engine.PairEntry.Pair;
39
40 public class DictFileParser {
41   
42   static final Logger logger = Logger.getLogger(DictFileParser.class.getName());
43
44   // Dictcc
45   public static final Pattern TAB = Pattern.compile("\\t");
46
47   // Chemnitz
48   public static final Pattern DOUBLE_COLON = Pattern.compile(" :: ");
49   public static final Pattern PIPE = Pattern.compile("\\|");
50   
51   static final Pattern SPACES = Pattern.compile("\\s+");
52 //  static final Pattern DE_NOUN = Pattern.compile("([^ ]+) *\\{(m|f|n|pl)\\}");
53 //  static final Pattern EN_VERB = Pattern.compile("^to ([^ ]+)");
54   
55   static final Pattern BRACKETED = Pattern.compile("\\[([^]]+)\\]");
56   static final Pattern PARENTHESIZED = Pattern.compile("\\(([^)]+)\\)");
57   static final Pattern CURLY_BRACED = Pattern.compile("\\{([^}]+)\\}");
58   
59   static final Pattern NON_CHAR_DASH = Pattern.compile("[^-'\\p{L}0-9]+");
60   public static final Pattern NON_CHAR = Pattern.compile("[^\\p{L}0-9]+");
61
62   static final Pattern TRIM_PUNC = Pattern.compile("^[^\\p{L}0-9]+|[^\\p{L}0-9]+$");
63
64   final Charset charset;
65   final boolean flipCols;
66   
67   final Pattern fieldSplit;
68   final Pattern subfieldSplit;
69   
70   final DictionaryBuilder dictBuilder;
71   final IndexBuilder[] langIndexBuilders;
72   final IndexBuilder bothIndexBuilder;
73   
74   // final Set<String> alreadyDone = new HashSet<String>();
75     
76   public DictFileParser(final Charset charset, boolean flipCols,
77       final Pattern fieldSplit, final Pattern subfieldSplit,
78       final DictionaryBuilder dictBuilder, final IndexBuilder[] langIndexBuilders,
79       final IndexBuilder bothIndexBuilder) {
80     this.charset = charset;
81     this.flipCols = flipCols;
82     this.fieldSplit = fieldSplit;
83     this.subfieldSplit = subfieldSplit;
84     this.dictBuilder = dictBuilder;
85     this.langIndexBuilders = langIndexBuilders;
86     this.bothIndexBuilder = bothIndexBuilder;
87   }
88
89   public void parseFile(final File file) throws IOException {
90     final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
91     String line;
92     int count = 0;
93     while ((line = reader.readLine()) != null) {
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) {
109       logger.warning("Malformed line: " + 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();
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 Pair(subfields[0][i], subfields[1][i]));
149     }
150     final IndexedEntry entryData = new IndexedEntry(pairEntry);
151     
152     for (int l = 0; l < 2; ++l) {
153       // alreadyDone.clear();
154       
155       for (int j = 0; j < subfields[l].length; ++j) {
156         String subfield = subfields[l][j];
157         final IndexBuilder indexBuilder = langIndexBuilders[l];
158         if (indexBuilder.index.sortLanguage == Language.de) {
159           subfield = parseField_DE(indexBuilder, subfield, entryData, j);
160         } else if (indexBuilder.index.sortLanguage == Language.en) {
161           subfield = parseField_EN(indexBuilder, subfield, entryData, j);
162         }
163         parseFieldGeneric(indexBuilder, subfield, entryData, j, subfields[l].length);
164       }
165     }
166   }
167
168   private void parseFieldGeneric(final IndexBuilder indexBuilder, String field,
169       final IndexedEntry entryData, final int subfieldIdx, final int numSubFields) {
170     // remove bracketed and parenthesized stuff.
171     final StringBuilder bracketed = new StringBuilder(); 
172     final StringBuilder parenthesized = new StringBuilder();
173     
174     Matcher matcher;
175     while ((matcher = BRACKETED.matcher(field)).find()) {
176       bracketed.append(matcher.group(1)).append(" ");
177       field = matcher.replaceFirst(" ");
178     }
179
180     while ((matcher = PARENTHESIZED.matcher(field)).find()) {
181       parenthesized.append(matcher.group(1)).append(" ");
182       field = matcher.replaceFirst(" ");
183     }
184     
185     field = SPACES.matcher(field).replaceAll(" ").trim();
186
187     // split words on non -A-z0-9, do them.
188     final String[] tokens = NON_CHAR_DASH.split(field);
189
190     final EntryTypeName entryTypeName;
191     if (numSubFields == 1) {
192       assert subfieldIdx == 0;
193       if (tokens.length == 1) {
194         entryTypeName = EntryTypeName.ONE_WORD;
195       } else if (tokens.length == 2) {
196         entryTypeName = EntryTypeName.TWO_WORDS;
197       } else if (tokens.length == 3) {
198         entryTypeName = EntryTypeName.THREE_WORDS;
199       } else if (tokens.length == 4) {
200         entryTypeName = EntryTypeName.FOUR_WORDS;
201       } else {
202         entryTypeName = EntryTypeName.FIVE_OR_MORE_WORDS;
203       }
204     } else {
205       assert numSubFields > 1;
206       if (subfieldIdx == 0) {
207         if (tokens.length == 1) {
208           entryTypeName = EntryTypeName.MULTIROW_HEAD_ONE_WORD;
209         } else {
210           entryTypeName = EntryTypeName.MULTIROW_HEAD_MANY_WORDS;
211         }
212       } else {
213         assert subfieldIdx > 0;
214         if (tokens.length == 1) {
215           entryTypeName = EntryTypeName.MULTIROW_TAIL_ONE_WORD;
216         } else {
217           entryTypeName = EntryTypeName.MULTIROW_TAIL_MANY_WORDS;
218         }
219       }
220     }
221
222     for (String token : tokens) {
223       token = TRIM_PUNC.matcher(token).replaceAll("");
224       if (/*!alreadyDone.contains(token) && */token.length() > 0) {
225         indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), entryTypeName);
226         // alreadyDone.add(token);
227         
228         // also split words on dashes, do them, too.
229         if (token.contains("-")) {
230           final String[] dashed = token.split("-");
231           for (final String dashedToken : dashed) {
232             if (/*!alreadyDone.contains(dashedToken) && */dashedToken.length() > 0) {
233               indexBuilder.addEntryWithTokens(entryData, Collections.singleton(dashedToken), EntryTypeName.PART_OF_HYPHENATED);
234             }
235           }
236         }
237
238       }  // if (!alreadyDone.contains(token)) {
239     }  // for (final String token : tokens) { 
240     
241     // process bracketed stuff (split on spaces and dashes always)
242     final String[] bracketedTokens = NON_CHAR.split(bracketed.toString());
243     for (final String token : bracketedTokens) {
244       assert !token.contains("-");
245       if (/*!alreadyDone.contains(token) && */token.length() > 0) {
246         indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), EntryTypeName.BRACKETED);
247       }
248     }
249     
250     // process paren stuff
251     final String[] parenTokens = NON_CHAR.split(parenthesized.toString());
252     for (final String token : parenTokens) {
253       assert !token.contains("-");
254       if (/*!alreadyDone.contains(token) && */token.length() > 0) {
255         indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), EntryTypeName.PARENTHESIZED);
256       }
257     }
258     
259   }
260
261   private String parseField_DE(final IndexBuilder indexBuilder, String field,
262       final IndexedEntry entryData, final int subfieldIdx) {
263     
264 //    final Matcher matcher = DE_NOUN.matcher(field);
265 //    while (matcher.find()) {
266 //      final String noun = matcher.group(1);
267       //final String gender = matcher.group(2);
268 //      if (alreadyDone.add(noun)) {
269         // System.out.println("Found DE noun " + noun + ", " + gender);
270 //        final List<EntryData> entries = indexBuilder.getOrCreateEntries(noun, EntryTypeName.NOUN);
271 //        entries.add(entryData);
272 //      }
273 //    }
274
275     // In English, curly braces are used for different tenses.
276     field = CURLY_BRACED.matcher(field).replaceAll(" ");
277
278     return field;
279   }
280   
281   private String parseField_EN(final IndexBuilder indexBuilder, String field,
282       final IndexedEntry entryData, final int subfieldIdx) {
283     if (field.startsWith("to ")) {
284       field = field.substring(3);
285     }
286     return field;
287   }
288   
289   public static final Set<String> tokenize(final String text, final Pattern pattern) {
290     final String[] split = pattern.split(text);
291     final Set<String> result = new LinkedHashSet<String>(Arrays.asList(split));
292     result.remove("");
293     return result;
294   }
295
296
297 }