1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
5 // http://www.apache.org/licenses/LICENSE-2.0
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
13 package com.hughes.android.dictionary.parser;
15 import java.io.BufferedReader;
17 import java.io.FileInputStream;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.nio.charset.Charset;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.LinkedHashSet;
25 import java.util.logging.Logger;
26 import java.util.regex.Matcher;
27 import java.util.regex.Pattern;
29 import com.hughes.android.dictionary.engine.DictionaryBuilder;
30 import com.hughes.android.dictionary.engine.EntrySource;
31 import com.hughes.android.dictionary.engine.EntryTypeName;
32 import com.hughes.android.dictionary.engine.HtmlEntry;
33 import com.hughes.android.dictionary.engine.IndexBuilder;
34 import com.hughes.android.dictionary.engine.IndexBuilder.TokenData;
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 import com.hughes.util.StringUtil;
40 public class SingleDictFileParser implements Parser {
42 static final Logger logger = Logger.getLogger(SingleDictFileParser.class.getName());
45 public static final String TAB = "\t";
48 public static final String DOUBLE_COLON = " :: ";
49 public static final String PIPE = "|";
51 static final Pattern SPACES = Pattern.compile("\\s+");
53 static final Pattern CURLY_BRACED = Pattern.compile("\\{([^}]+)\\}");
55 // http://www.regular-expressions.info/unicode.html
56 static final Pattern NON_CHAR_DASH = Pattern.compile("[^-'\\p{L}\\p{M}\\p{N}]+");
57 public static final Pattern NON_CHAR = Pattern.compile("[^\\p{L}\\p{M}\\p{N}]+");
59 static final Pattern TRIM_PUNC = Pattern.compile("^[^\\p{L}\\p{M}\\p{N}]+|[^\\p{L}\\p{M}\\p{N}]+$");
61 final Charset charset;
63 final String fieldSplit;
65 final DictionaryBuilder dictBuilder;
67 EntrySource entrySource;
69 // final Set<String> alreadyDone = new HashSet<String>();
71 public SingleDictFileParser(final Charset charset,
72 final String fieldSplit,
73 final DictionaryBuilder dictBuilder) {
74 this.charset = charset;
75 this.fieldSplit = fieldSplit;
76 this.dictBuilder = dictBuilder;
80 public void parse(final File file, final EntrySource entrySouce, final int pageLimit) throws IOException {
81 this.entrySource = entrySouce;
82 final BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
85 while ((line = reader.readLine()) != null) {
86 if (pageLimit >= 0 && count >= pageLimit) {
89 if (count % 10000 == 0) {
90 logger.info("count=" + count + ", line=" + line);
97 private void parseLine(final String line) {
98 if (line.startsWith("#") || line.isEmpty()) {
99 logger.info("Skipping comment line: " + line);
102 final String[] fields = StringUtil.split(line, fieldSplit);
103 if (fields.length < 2 || fields.length > 4) {
104 logger.warning("Malformed line, expected 3 or 4 fields, got " + fields.length + ": " + line);
108 String headword = SPACES.matcher(fields[0]).replaceAll(" ").trim();
109 String definition = SPACES.matcher(fields[1]).replaceAll(" ").trim();
111 final HtmlEntry htmlEntry = new HtmlEntry(entrySource, headword);
112 htmlEntry.html = definition;
113 IndexedEntry entryData = new IndexedEntry(htmlEntry);
114 entryData.isValid = true;
116 final IndexBuilder titleIndexBuilder = dictBuilder.indexBuilders.get(0);
117 final TokenData tokenData = titleIndexBuilder.getOrCreateTokenData(headword);
118 tokenData.hasMainEntry = true;
120 htmlEntry.addToDictionary(titleIndexBuilder.index.dict);
121 tokenData.htmlEntries.add(htmlEntry);
126 private StringBuilder extractParenthesized(StringBuilder in, String startChar, String endChar) {
127 StringBuilder res = new StringBuilder();
129 while ((pos = in.indexOf(startChar, pos)) != -1) {
130 int end = in.indexOf(endChar, pos + 1);
131 if (end == -1) break;
132 res.append(in, pos + 1, end).append(" ");
133 in.replace(pos, end + 1, " ");
134 pos++; // skip the just appended space
139 private void parseFieldGeneric(final IndexBuilder indexBuilder, String field,
140 final IndexedEntry entryData, final int subfieldIdx, final int numSubFields) {
141 final StringBuilder fieldsb = new StringBuilder(field);
142 // remove bracketed and parenthesized stuff.
143 final StringBuilder bracketed = extractParenthesized(fieldsb, "[", "]");
144 final StringBuilder parenthesized = extractParenthesized(fieldsb, "(", ")");
146 field = fieldsb.toString().trim();
148 // split words on non -A-z0-9, do them.
149 final String[] tokens = NON_CHAR_DASH.split(field);
151 final EntryTypeName entryTypeName;
152 if (numSubFields == 1) {
153 assert subfieldIdx == 0;
154 if (tokens.length == 1) {
155 entryTypeName = EntryTypeName.ONE_WORD;
156 } else if (tokens.length == 2) {
157 entryTypeName = EntryTypeName.TWO_WORDS;
158 } else if (tokens.length == 3) {
159 entryTypeName = EntryTypeName.THREE_WORDS;
160 } else if (tokens.length == 4) {
161 entryTypeName = EntryTypeName.FOUR_WORDS;
163 entryTypeName = EntryTypeName.FIVE_OR_MORE_WORDS;
166 assert numSubFields > 1;
167 if (subfieldIdx == 0) {
168 if (tokens.length == 1) {
169 entryTypeName = EntryTypeName.MULTIROW_HEAD_ONE_WORD;
171 entryTypeName = EntryTypeName.MULTIROW_HEAD_MANY_WORDS;
174 assert subfieldIdx > 0;
175 if (tokens.length == 1) {
176 entryTypeName = EntryTypeName.MULTIROW_TAIL_ONE_WORD;
178 entryTypeName = EntryTypeName.MULTIROW_TAIL_MANY_WORDS;
183 for (String token : tokens) {
184 token = TRIM_PUNC.matcher(token).replaceAll("");
185 if (/*!alreadyDone.contains(token) && */!token.isEmpty()) {
186 indexBuilder.addEntryWithTokens(entryData, Collections.singleton(token), entryTypeName);
187 // alreadyDone.add(token);
189 // also split words on dashes, do them, too.
190 if (token.indexOf('-') != -1) {
191 final String[] dashed = StringUtil.split(token, "-");
192 for (final String dashedToken : dashed) {
193 if (/*!alreadyDone.contains(dashedToken) && */!dashedToken.isEmpty()) {
194 indexBuilder.addEntryWithTokens(entryData, Collections.singleton(dashedToken), EntryTypeName.PART_OF_HYPHENATED);
199 } // if (!alreadyDone.contains(token)) {
200 } // for (final String token : tokens) {
203 public static Set<String> tokenize(final String text, final Pattern pattern) {
204 final String[] split = pattern.split(text);
205 final Set<String> result = new LinkedHashSet<>(Arrays.asList(split));