]> gitweb.fperrin.net Git - DictionaryPC.git/blob - src/com/hughes/android/dictionary/parser/DictFileParser.java
Stoplists, fix location of wikisplits.
[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       pairEntry.pairs.add(new Pair(subfields[0][i], subfields[1][i]));
139     }
140     final IndexedEntry entryData = new IndexedEntry(pairEntry);
141     
142     for (int l = 0; l < 2; ++l) {
143       // alreadyDone.clear();
144       
145       for (int j = 0; j < subfields[l].length; ++j) {
146         String subfield = subfields[l][j];
147         final IndexBuilder indexBuilder = langIndexBuilders[l];
148         if (indexBuilder.index.sortLanguage == Language.de) {
149           subfield = parseField_DE(indexBuilder, subfield, entryData, j);
150         } else if (indexBuilder.index.sortLanguage == Language.en) {
151           subfield = parseField_EN(indexBuilder, subfield, entryData, j);
152         }
153         parseFieldGeneric(indexBuilder, subfield, entryData, j, subfields[l].length);
154       }
155     }
156   }
157
158   private void parseFieldGeneric(final IndexBuilder indexBuilder, String field,
159       final IndexedEntry entryData, final int subfieldIdx, final int numSubFields) {
160     // remove bracketed and parenthesized stuff.
161     final StringBuilder bracketed = new StringBuilder(); 
162     final StringBuilder parenthesized = new StringBuilder();
163     
164     Matcher matcher;
165     while ((matcher = BRACKETED.matcher(field)).find()) {
166       bracketed.append(matcher.group(1)).append(" ");
167       field = matcher.replaceFirst(" ");
168     }
169
170     while ((matcher = PARENTHESIZED.matcher(field)).find()) {
171       parenthesized.append(matcher.group(1)).append(" ");
172       field = matcher.replaceFirst(" ");
173     }
174     
175     field = SPACES.matcher(field).replaceAll(" ").trim();
176
177     // split words on non -A-z0-9, do them.
178     final String[] tokens = NON_CHAR_DASH.split(field);
179
180     final EntryTypeName entryTypeName;
181     if (numSubFields == 1) {
182       assert subfieldIdx == 0;
183       if (tokens.length == 1) {
184         entryTypeName = EntryTypeName.ONE_WORD;
185       } else if (tokens.length == 2) {
186         entryTypeName = EntryTypeName.TWO_WORDS;
187       } else if (tokens.length == 3) {
188         entryTypeName = EntryTypeName.THREE_WORDS;
189       } else if (tokens.length == 4) {
190         entryTypeName = EntryTypeName.FOUR_WORDS;
191       } else {
192         entryTypeName = EntryTypeName.FIVE_OR_MORE_WORDS;
193       }
194     } else {
195       assert numSubFields > 1;
196       if (subfieldIdx == 0) {
197         if (tokens.length == 1) {
198           entryTypeName = EntryTypeName.MULTIROW_HEAD_ONE_WORD;
199         } else {
200           entryTypeName = EntryTypeName.MULTIROW_HEAD_MANY_WORDS;
201         }
202       } else {
203         assert subfieldIdx > 0;
204         if (tokens.length == 1) {
205           entryTypeName = EntryTypeName.MULTIROW_TAIL_ONE_WORD;
206         } else {
207           entryTypeName = EntryTypeName.MULTIROW_TAIL_MANY_WORDS;
208         }
209       }
210     }
211
212     for (String token : tokens) {
213       token = TRIM_PUNC.matcher(token).replaceAll("");
214       if (/*!alreadyDone.contains(token) && */token.length() > 0) {
215         indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), entryTypeName);
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               indexBuilder.addEntryWithTokens(entryData, Collections.singleton(dashedToken), EntryTypeName.PART_OF_HYPHENATED);
224             }
225           }
226         }
227
228       }  // if (!alreadyDone.contains(token)) {
229     }  // for (final String token : tokens) { 
230     
231     // process bracketed stuff (split on spaces and dashes always)
232     final String[] bracketedTokens = NON_CHAR.split(bracketed.toString());
233     for (final String token : bracketedTokens) {
234       assert !token.contains("-");
235       if (/*!alreadyDone.contains(token) && */token.length() > 0) {
236         indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), EntryTypeName.BRACKETED);
237       }
238     }
239     
240     // process paren stuff
241     final String[] parenTokens = NON_CHAR.split(parenthesized.toString());
242     for (final String token : parenTokens) {
243       assert !token.contains("-");
244       if (/*!alreadyDone.contains(token) && */token.length() > 0) {
245         indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), EntryTypeName.PARENTHESIZED);
246       }
247     }
248     
249   }
250
251   private String parseField_DE(final IndexBuilder indexBuilder, String field,
252       final IndexedEntry entryData, final int subfieldIdx) {
253     
254 //    final Matcher matcher = DE_NOUN.matcher(field);
255 //    while (matcher.find()) {
256 //      final String noun = matcher.group(1);
257       //final String gender = matcher.group(2);
258 //      if (alreadyDone.add(noun)) {
259         // System.out.println("Found DE noun " + noun + ", " + gender);
260 //        final List<EntryData> entries = indexBuilder.getOrCreateEntries(noun, EntryTypeName.NOUN);
261 //        entries.add(entryData);
262 //      }
263 //    }
264
265     // In English, curly braces are used for different tenses.
266     field = CURLY_BRACED.matcher(field).replaceAll(" ");
267
268     return field;
269   }
270   
271   private String parseField_EN(final IndexBuilder indexBuilder, String field,
272       final IndexedEntry entryData, final int subfieldIdx) {
273     if (field.startsWith("to ")) {
274       field = field.substring(3);
275     }
276     return field;
277   }
278   
279   public static final Set<String> tokenize(final String text, final Pattern pattern) {
280     final String[] split = pattern.split(text);
281     final Set<String> result = new LinkedHashSet<String>(Arrays.asList(split));
282     result.remove("");
283     return result;
284   }
285
286
287 }