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