1 // Copyright 2011 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 package com.hughes.android.dictionary.parser;
17 import java.io.BufferedInputStream;
18 import java.io.DataInputStream;
19 import java.io.EOFException;
21 import java.io.FileInputStream;
22 import java.io.IOException;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collection;
26 import java.util.LinkedHashSet;
27 import java.util.List;
30 import java.util.logging.Logger;
31 import java.util.regex.Pattern;
33 import com.hughes.android.dictionary.engine.EntryTypeName;
34 import com.hughes.android.dictionary.engine.IndexBuilder;
35 import com.hughes.android.dictionary.engine.IndexedEntry;
36 import com.hughes.android.dictionary.engine.PairEntry;
37 import com.hughes.android.dictionary.engine.PairEntry.Pair;
39 public class EnWiktionaryXmlParser {
41 private static final String TRANSLITERATION_FORMAT = " (tr. %s)";
43 static final Logger LOG = Logger.getLogger(EnWiktionaryXmlParser.class.getName());
45 // TODO: process {{ttbc}} lines
47 static final Pattern partOfSpeechHeader = Pattern.compile(
48 "Noun|Verb|Adjective|Adverb|Pronoun|Conjunction|Interjection|" +
49 "Preposition|Proper noun|Article|Prepositional phrase|Acronym|" +
50 "Abbreviation|Initialism|Contraction|Prefix|Suffix|Symbol|Letter|" +
51 "Ligature|Idiom|Phrase|\\{\\{acronym\\}\\}|\\{\\{initialism\\}\\}|" +
52 // These are @deprecated:
53 "Noun form|Verb form|Adjective form|Nominal phrase|Noun phrase|" +
54 "Verb phrase|Transitive verb|Intransitive verb|Reflexive verb|" +
55 // These are extras I found:
56 "Determiner|Numeral|Number|Cardinal number|Ordinal number|Proverb|" +
57 "Particle|Interjection|Pronominal adverb" +
58 "Han character|Hanzi|Hanja|Kanji|Katakana character|Syllable");
60 final IndexBuilder enIndexBuilder;
61 final IndexBuilder otherIndexBuilder;
62 final Pattern langPattern;
63 final Pattern langCodePattern;
66 public EnWiktionaryXmlParser(final IndexBuilder enIndexBuilder, final IndexBuilder otherIndexBuilder, final Pattern langPattern, final Pattern langCodePattern, final boolean swap) {
67 this.enIndexBuilder = enIndexBuilder;
68 this.otherIndexBuilder = otherIndexBuilder;
69 this.langPattern = langPattern;
70 this.langCodePattern = langCodePattern;
75 public void parse(final File file, final int pageLimit) throws IOException {
77 final DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
79 if (pageLimit >= 0 && pageCount >= pageLimit) {
85 title = dis.readUTF();
86 } catch (EOFException e) {
90 final String heading = dis.readUTF();
91 final int bytesLength = dis.readInt();
92 final byte[] bytes = new byte[bytesLength];
94 final String text = new String(bytes, "UTF8");
96 parseSection(title, heading, text);
99 if (pageCount % 1000 == 0) {
100 LOG.info("pageCount=" + pageCount);
105 private void parseSection(final String title, String heading, final String text) {
106 if (title.startsWith("Wiktionary:") ||
107 title.startsWith("Template:") ||
108 title.startsWith("Appendix:") ||
109 title.startsWith("Category:") ||
110 title.startsWith("Index:") ||
111 title.startsWith("MediaWiki:") ||
112 title.startsWith("TransWiki:") ||
113 title.startsWith("Citations:") ||
114 title.startsWith("Concordance:") ||
115 title.startsWith("Help:")) {
119 heading = heading.replaceAll("=", "").trim();
120 if (heading.equals("English")) {
121 doEnglishWord(title, text);
122 } else if (langPattern.matcher(heading).find()){
123 doForeignWord(heading, title, text);
128 // -------------------------------------------------------------------------
130 private void doEnglishWord(String title, String text) {
135 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
136 while (wikiTokenizer.nextToken() != null) {
138 if (wikiTokenizer.isHeading()) {
139 final String headerName = wikiTokenizer.headingWikiText();
141 if (wikiTokenizer.headingDepth() <= posDepth) {
146 if (partOfSpeechHeader.matcher(headerName).matches()) {
147 posDepth = wikiTokenizer.headingDepth();
148 pos = wikiTokenizer.headingWikiText();
149 // TODO: if we're inside the POS section, we should handle the first title line...
151 } else if (headerName.equals("Translations")) {
153 LOG.warning("Translations without POS: " + title);
155 doTranslations(title, wikiTokenizer, pos);
156 } else if (headerName.equals("Pronunciation")) {
157 //doPronunciation(wikiLineReader);
164 private static Set<String> encodings = new LinkedHashSet<String>(Arrays.asList("zh-ts",
165 "sd-Arab", "ku-Arab", "Arab", "unicode", "Laoo", "ur-Arab", "Thai",
166 "fa-Arab", "Khmr", "zh-tsp", "Cyrl", "IPAchar", "ug-Arab", "ko-inline",
167 "Jpan", "Kore", "Hebr", "rfscript", "Beng", "Mong", "Knda", "Cyrs",
168 "yue-tsj", "Mlym", "Tfng", "Grek", "yue-yue-j"));
170 private void doTranslations(final String title, final WikiTokenizer wikiTokenizer, final String pos) {
171 if (title.equals("absolutely")) {
172 //System.out.println();
175 String topLevelLang = null;
177 boolean done = false;
178 while (wikiTokenizer.nextToken() != null) {
179 if (wikiTokenizer.isHeading()) {
180 wikiTokenizer.returnToLineStart();
187 // Check whether we care about this line:
189 if (wikiTokenizer.isFunction()) {
190 final String functionName = wikiTokenizer.functionName();
191 final List<String> positionArgs = wikiTokenizer.functionPositionArgs();
193 if (functionName.equals("trans-top")) {
195 if (wikiTokenizer.functionPositionArgs().size() >= 1) {
196 sense = positionArgs.get(0);
197 // TODO: could emphasize words in [[brackets]] inside sense.
198 sense = WikiTokenizer.toPlainText(sense);
199 //LOG.info("Sense: " + sense);
201 } else if (functionName.equals("trans-bottom")) {
203 } else if (functionName.equals("trans-mid")) {
204 } else if (functionName.equals("trans-see")) {
205 // TODO: would also be nice...
206 } else if (functionName.startsWith("picdic")) {
207 } else if (functionName.startsWith("checktrans")) {
209 } else if (functionName.startsWith("ttbc")) {
210 wikiTokenizer.nextLine();
211 // TODO: would be great to handle ttbc
212 // TODO: Check this: done = true;
214 LOG.warning("Unexpected translation wikifunction: " + wikiTokenizer.token() + ", title=" + title);
216 } else if (wikiTokenizer.isListItem()) {
217 final String line = wikiTokenizer.listItemWikiText();
218 // This line could produce an output...
220 if (line.contains("ich hoan dich gear")) {
221 //System.out.println();
224 // First strip the language and check whether it matches.
225 // And hold onto it for sub-lines.
226 final int colonIndex = line.indexOf(":");
227 if (colonIndex == -1) {
231 final String lang = trim(WikiTokenizer.toPlainText(line.substring(0, colonIndex)));
232 final boolean appendLang;
233 if (wikiTokenizer.listItemPrefix().length() == 1) {
235 final boolean thisFind = langPattern.matcher(lang).find();
239 appendLang = !langPattern.matcher(lang).matches();
240 } else if (topLevelLang == null) {
243 // Two-level -- the only way we won't append is if this second level matches exactly.
244 if (!langPattern.matcher(lang).matches() && !langPattern.matcher(topLevelLang).find()) {
247 appendLang = !langPattern.matcher(lang).matches();
250 String rest = line.substring(colonIndex + 1).trim();
251 if (rest.length() > 0) {
252 doTranslationLine(line, appendLang ? lang : null, title, pos, sense, rest);
255 } else if (wikiTokenizer.remainderStartsWith("''See''")) {
256 wikiTokenizer.nextLine();
257 LOG.fine("Skipping line: " + wikiTokenizer.token());
258 } else if (wikiTokenizer.isWikiLink()) {
259 final String wikiLink = wikiTokenizer.wikiLinkText();
260 if (wikiLink.contains(":") && wikiLink.contains(title)) {
261 } else if (wikiLink.contains("Category:")) {
263 LOG.warning("Unexpected wikiLink: " + wikiTokenizer.token() + ", title=" + title);
265 } else if (wikiTokenizer.isNewline() || wikiTokenizer.isMarkup() || wikiTokenizer.isComment()) {
267 final String token = wikiTokenizer.token();
268 if (token.equals("----")) {
270 LOG.warning("Unexpected translation token: " + wikiTokenizer.token() + ", title=" + title);
277 private static <T> T get(final List<T> list, final int index) {
278 return index < list.size() ? list.get(index) : null;
281 private void doTranslationLine(final String line, final String lang, final String title, final String pos, final String sense, final String rest) {
282 // Good chance we'll actually file this one...
283 final PairEntry pairEntry = new PairEntry();
284 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
286 final StringBuilder otherText = new StringBuilder();
287 final WikiTokenizer wikiTokenizer = new WikiTokenizer(rest, false);
288 while (wikiTokenizer.nextToken() != null) {
290 if (wikiTokenizer.isPlainText()) {
291 final String plainText = wikiTokenizer.token();
292 otherText.append("").append(plainText);
293 otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
295 } else if (wikiTokenizer.isWikiLink()) {
296 final String plainText = wikiTokenizer.wikiLinkText();
297 otherText.append("").append(plainText);
298 otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_WIKI_TEXT);
300 } else if (wikiTokenizer.isFunction()) {
301 final String functionName = wikiTokenizer.functionName();
302 final List<String> args = wikiTokenizer.functionPositionArgs();
303 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
305 if (functionName.equals("t") || functionName.equals("t+") || functionName.equals("t-") || functionName.equals("tø") || functionName.equals("apdx-t")) {
306 if (args.size() < 2) {
307 LOG.warning("{{t}} with too few args: " + line + ", title=" + title);
310 final String langCode = get(args, 0);
311 //if (this.langCodePattern.matcher(langCode).matches()) {
312 final String word = get(args, 1);
313 final String gender = get(args, 2);
314 final String transliteration = namedArgs.get("tr");
315 if (otherText.length() > 0) {
316 otherText.append("");
318 otherText.append(word);
319 otherIndexBuilder.addEntryWithString(indexedEntry, word, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
320 if (gender != null) {
321 otherText.append(String.format(" {%s}", gender));
323 if (transliteration != null) {
324 otherText.append(String.format(TRANSLITERATION_FORMAT, transliteration));
325 otherIndexBuilder.addEntryWithString(indexedEntry, transliteration, EntryTypeName.WIKTIONARY_TRANSLITERATION);
328 } else if (functionName.equals("qualifier")) {
329 if (args.size() == 0) {
330 otherText.append(wikiTokenizer.token());
332 String qualifier = args.get(0);
333 if (!namedArgs.isEmpty() || args.size() > 1) {
334 LOG.warning("weird qualifier: " + line);
337 otherText.append("(").append(qualifier).append(")");
339 } else if (encodings.contains(functionName)) {
340 otherText.append("").append(args.get(0));
341 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
342 } else if (isGender(functionName)) {
343 appendGender(otherText, functionName, args);
344 } else if (functionName.equals("g")) {
345 otherText.append("{g}");
346 } else if (functionName.equals("l")) {
347 // encodes text in various langs.
349 otherText.append("").append(args.get(1));
350 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(1), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
351 // TODO: transliteration
352 } else if (functionName.equals("term")) {
353 // cross-reference to another dictionary
354 otherText.append("").append(args.get(0));
355 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
356 // TODO: transliteration
357 } else if (functionName.equals("italbrac") || functionName.equals("gloss")) {
358 // TODO: put this text aside to use it.
359 otherText.append("[").append(args.get(0)).append("]");
360 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
361 } else if (functionName.equals("ttbc")) {
362 LOG.warning("Unexpected {{ttbc}}");
363 } else if (functionName.equals("trreq")) {
364 } else if (functionName.equals("not used")) {
365 otherText.append("(not used)");
366 } else if (functionName.equals("t-image")) {
367 // American sign language
370 otherText.append(wikiTokenizer.token());
373 } else if (wikiTokenizer.isNewline()) {
375 } else if (wikiTokenizer.isComment()) {
376 } else if (wikiTokenizer.isMarkup()) {
378 LOG.warning("Bad translation token: " + wikiTokenizer.token());
381 if (otherText.length() == 0) {
382 LOG.warning("Empty otherText: " + line);
387 otherText.insert(0, String.format("(%s) ", lang));
390 StringBuilder englishText = new StringBuilder();
392 englishText.append(title);
394 englishText.append(" (").append(sense).append(")");
395 enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
398 englishText.append(" (").append(pos.toLowerCase()).append(")");
400 enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
402 final Pair pair = new Pair(trim(englishText.toString()), trim(otherText.toString()), swap);
403 pairEntry.pairs.add(pair);
404 if (!pairsAdded.add(pair.toString())) {
405 LOG.warning("Duplicate pair: " + pair.toString());
407 if (pair.toString().equals("libero {m} :: free (adjective)")) {
408 System.out.println();
414 private void appendGender(final StringBuilder otherText,
415 final String functionName, final List<String> args) {
416 otherText.append("{");
417 otherText.append(functionName);
418 for (int i = 0; i < args.size(); ++i) {
419 otherText.append("|").append(args.get(i));
421 otherText.append("}");
425 private boolean isGender(final String functionName) {
426 return functionName.equals("m") || functionName.equals("f") || functionName.equals("n") || functionName.equals("p");
429 Set<String> pairsAdded = new LinkedHashSet<String>();
431 // -------------------------------------------------------------------------
433 private void doForeignWord(final String lang, final String title, final String text) {
434 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
435 while (wikiTokenizer.nextToken() != null) {
436 if (wikiTokenizer.isHeading()) {
437 final String headingName = wikiTokenizer.headingWikiText();
438 if (headingName.equals("Translations")) {
439 LOG.warning("Translations not in English section: " + title);
440 } else if (headingName.equals("Pronunciation")) {
441 //doPronunciation(wikiLineReader);
442 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
443 doForeignPartOfSpeech(lang, title, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
450 static final class ListSection {
451 final String firstPrefix;
452 final String firstLine;
453 final List<String> nextPrefixes = new ArrayList<String>();
454 final List<String> nextLines = new ArrayList<String>();
456 public ListSection(String firstPrefix, String firstLine) {
457 this.firstPrefix = firstPrefix;
458 this.firstLine = firstLine;
462 public String toString() {
463 return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
468 int foreignCount = 0;
469 private void doForeignPartOfSpeech(final String lang, String title, final String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
470 if (++foreignCount % 1000 == 0) {
471 LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
473 if (title.equals("moro")) {
474 System.out.println();
477 final StringBuilder foreignBuilder = new StringBuilder();
478 final Collection<String> wordForms = new ArrayList<String>();
479 final List<ListSection> listSections = new ArrayList<ListSection>();
483 ListSection lastListSection = null;
485 int currentHeadingDepth = posDepth;
486 while (wikiTokenizer.nextToken() != null) {
487 if (wikiTokenizer.isHeading()) {
488 currentHeadingDepth = wikiTokenizer.headingDepth();
490 if (currentHeadingDepth <= posDepth) {
491 wikiTokenizer.returnToLineStart();
496 if (currentHeadingDepth > posDepth) {
497 // TODO: deal with other neat info sections
501 if (wikiTokenizer.isFunction()) {
502 final String name = wikiTokenizer.functionName();
503 final List<String> args = wikiTokenizer.functionPositionArgs();
504 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
505 // First line is generally a repeat of the title with some extra information.
506 // We need to build up the left side (foreign text, tokens) separately from the
507 // right side (English). The left-side may get paired with multiple right sides.
508 // The left side should get filed under every form of the word in question (singular, plural).
510 // For verbs, the conjugation comes later on in a deeper section.
511 // Ideally, we'd want to file every English entry with the verb
512 // under every verb form coming from the conjugation.
513 // Ie. under "fa": see: "make :: fare" and "do :: fare"
514 // But then where should we put the conjugation table?
515 // I think just under fare. But then we need a way to link to the entry (actually the row, since entries doesn't show up!)
516 // for the conjugation table from "fa".
517 // Would like to be able to link to a lang#token.
518 if (isGender(name)) {
519 appendGender(foreignBuilder, name, args);
520 } else if (name.equals("wikipedia")) {
521 namedArgs.remove("lang");
522 if (args.size() > 1 || !namedArgs.isEmpty()) {
524 foreignBuilder.append(wikiTokenizer.token());
525 } else if (args.size() == 1) {
526 foreignBuilder.append(wikiTokenizer.token());
528 //foreignBuilder.append(title);
530 } else if (name.equals("attention") || name.equals("zh-attention")) {
531 // See: http://en.wiktionary.org/wiki/Template:attention
533 } else if (name.equals("infl")) {
534 // See: http://en.wiktionary.org/wiki/Template:infl
535 final String langCode = get(args, 0);
536 namedArgs.remove("sc");
537 final String tr = namedArgs.remove("tr");
538 final String g = namedArgs.remove("g");
539 final String g2 = namedArgs.remove("g2");
540 final String g3 = namedArgs.remove("g3");
541 if (!namedArgs.isEmpty()) {
542 LOG.warning("Didn't parse infl: " + wikiTokenizer.token());
543 foreignBuilder.append(wikiTokenizer.token());
545 String head = namedArgs.get("head");
549 head = WikiTokenizer.toPlainText(head);
551 foreignBuilder.append(head);
554 foreignBuilder.append(" {").append(g);
556 foreignBuilder.append("|").append(g2);
559 foreignBuilder.append("|").append(g3);
561 foreignBuilder.append("}");
565 foreignBuilder.append(String.format(TRANSLITERATION_FORMAT, tr));
569 final String pos = get(args, 1);
571 foreignBuilder.append(" (").append(pos).append(")");
573 for (int i = 2; i < args.size(); i += 2) {
574 final String inflName = get(args, i);
575 final String inflValue = get(args, i + 1);
576 foreignBuilder.append(", ").append(WikiTokenizer.toPlainText(inflName));
577 if (inflValue != null && inflValue.length() > 0) {
578 foreignBuilder.append(": ").append(WikiTokenizer.toPlainText(inflValue));
579 wordForms.add(inflValue);
583 } else if (name.equals("it-noun")) {
584 final String base = get(args, 0);
585 final String gender = get(args, 1);
586 final String singular = base + get(args, 2);
587 final String plural = base + get(args, 3);
588 foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
589 wordForms.add(singular);
590 wordForms.add(plural);
591 } else if (name.equals("it-proper noun")) {
592 foreignBuilder.append(wikiTokenizer.token());
593 } else if (name.equals("it-adj")) {
594 foreignBuilder.append(wikiTokenizer.token());
595 } else if (name.startsWith("it-conj")) {
596 if (name.equals("it-conj-are")) {
597 itConjAre(args, namedArgs);
598 } else if (name.equals("it-conj-ere")) {
599 } else if (name.equals("it-conj-ire")) {
601 LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
605 foreignBuilder.append(wikiTokenizer.token());
606 // LOG.warning("Unknown function: " + wikiTokenizer.token());
609 } else if (wikiTokenizer.isListItem()) {
610 final String prefix = wikiTokenizer.listItemPrefix();
611 if (lastListSection != null &&
612 prefix.startsWith(lastListSection.firstPrefix) &&
613 prefix.length() > lastListSection.firstPrefix.length()) {
614 lastListSection.nextPrefixes.add(prefix);
615 lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
617 lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
618 listSections.add(lastListSection);
620 } else if (lastListSection != null) {
621 // Don't append anything after the lists, because there's crap.
622 } else if (wikiTokenizer.isWikiLink()) {
624 foreignBuilder.append(wikiTokenizer.wikiLinkText());
626 } else if (wikiTokenizer.isPlainText()) {
628 foreignBuilder.append(wikiTokenizer.token());
630 } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
633 LOG.warning("Unexpected token: " + wikiTokenizer.token());
638 // Here's where we exit.
639 // Should we make an entry even if there are no foreign list items?
640 String foreign = foreignBuilder.toString().trim();
641 if (!foreign.toLowerCase().startsWith(title.toLowerCase())) {
642 foreign = String.format("%s %s", title, foreign);
644 if (!langPattern.matcher(lang).matches()) {
645 foreign = String.format("(%s) %s", lang, foreign);
647 for (final ListSection listSection : listSections) {
648 doForeignListItem(foreign, title, wordForms, listSection);
654 static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
655 "(first|second|third)-person (singular|plural)|" +
661 private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
663 final String prefix = listSection.firstPrefix;
664 if (prefix.length() > 1) {
665 // Could just get looser and say that any prefix longer than first is a sublist.
666 LOG.warning("Prefix too long: " + listSection);
670 final PairEntry pairEntry = new PairEntry();
671 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
673 final StringBuilder englishBuilder = new StringBuilder();
675 final String mainLine = listSection.firstLine;
677 final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
678 while (englishTokenizer.nextToken() != null) {
679 // TODO handle form of....
680 if (englishTokenizer.isPlainText()) {
681 englishBuilder.append(englishTokenizer.token());
682 enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
683 } else if (englishTokenizer.isWikiLink()) {
684 final String text = englishTokenizer.wikiLinkText();
685 final String link = englishTokenizer.wikiLinkDest();
687 if (link.contains("#English")) {
688 englishBuilder.append(text);
689 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
690 } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
691 englishBuilder.append(text);
692 otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
693 } else if (link.equals("plural")) {
694 englishBuilder.append(text);
696 //LOG.warning("Special link: " + englishTokenizer.token());
697 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
698 englishBuilder.append(text);
702 englishBuilder.append(text);
703 if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
704 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
707 } else if (englishTokenizer.isFunction()) {
708 final String name = englishTokenizer.functionName();
709 if (name.contains("conjugation of ") ||
710 name.contains("form of ") ||
711 name.contains("feminine of ") ||
712 name.contains("plural of ")) {
713 // Ignore these in the index, they're really annoying....
714 englishBuilder.append(englishTokenizer.token());
716 englishBuilder.append(englishTokenizer.token());
717 // LOG.warning("Unexpected function: " + englishTokenizer.token());
720 if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
722 LOG.warning("Unexpected definition text: " + englishTokenizer.token());
727 final String english = trim(englishBuilder.toString());
728 if (english.length() > 0) {
729 final Pair pair = new Pair(english, trim(foreignText), this.swap);
730 pairEntry.pairs.add(pair);
731 otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
732 for (final String form : forms) {
733 otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_FORM_SINGLE, EntryTypeName.WIKTIONARY_FORM_MULTI);
738 String lastForeign = null;
739 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
740 final String nextPrefix = listSection.nextPrefixes.get(i);
741 final String nextLine = listSection.nextLines.get(i);
742 int dash = nextLine.indexOf("—");
745 dash = nextLine.indexOf("—");
749 dash = nextLine.indexOf(" - ");
753 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
754 final String foreignEx = nextLine.substring(0, dash);
755 final String englishEx = nextLine.substring(dash + mdashLen);
756 final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
757 if (pair.lang1 != "--" && pair.lang1 != "--") {
758 pairEntry.pairs.add(pair);
761 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
762 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
763 lastForeign = nextLine;
764 if (pair.lang1 != "--" && pair.lang1 != "--") {
765 pairEntry.pairs.add(pair);
767 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
768 if (lastForeign != null && pairEntry.pairs.size() > 0) {
769 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
770 final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
771 if (pair.lang1 != "--" && pair.lang1 != "--") {
772 pairEntry.pairs.add(pair);
776 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
777 // TODO: add something.
779 } else if (nextPrefix.equals("#*")) {
780 // Can't really index these.
781 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
782 lastForeign = nextLine;
783 if (pair.lang1 != "--" && pair.lang1 != "--") {
784 pairEntry.pairs.add(pair);
786 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
787 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
788 if (pair.lang1 != "--" && pair.lang1 != "--") {
789 pairEntry.pairs.add(pair);
797 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
798 final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
799 final StringBuilder builder = new StringBuilder();
800 boolean insideTripleQuotes = false;
801 while (wikiTokenizer.nextToken() != null) {
802 if (wikiTokenizer.isPlainText()) {
803 builder.append(wikiTokenizer.token());
804 if (indexBuilder != null) {
805 indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
807 } else if (wikiTokenizer.isWikiLink()) {
808 final String text = wikiTokenizer.wikiLinkText().replaceAll("'", "");
809 builder.append(text);
810 if (indexBuilder != null) {
811 indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
813 } else if (wikiTokenizer.isFunction()) {
814 builder.append(wikiTokenizer.token());
815 } else if (wikiTokenizer.isMarkup()) {
816 if (wikiTokenizer.token().equals("'''")) {
817 insideTripleQuotes = !insideTripleQuotes;
819 } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
822 LOG.warning("unexpected token: " + wikiTokenizer.token());
825 final String result = trim(builder.toString());
826 return result.length() > 0 ? result : "--";
830 private void itConjAre(List<String> args, Map<String, String> namedArgs) {
831 final String base = args.get(0);
832 final String aux = args.get(1);
834 putIfMissing(namedArgs, "inf", base + "are");
835 putIfMissing(namedArgs, "aux", aux);
836 putIfMissing(namedArgs, "ger", base + "ando");
837 putIfMissing(namedArgs, "presp", base + "ante");
838 putIfMissing(namedArgs, "pastp", base + "ato");
840 putIfMissing(namedArgs, "pres1s", base + "o");
841 putIfMissing(namedArgs, "pres2s", base + "i");
842 putIfMissing(namedArgs, "pres3s", base + "a");
843 putIfMissing(namedArgs, "pres1p", base + "iamo");
844 putIfMissing(namedArgs, "pres2p", base + "ate");
845 putIfMissing(namedArgs, "pres3p", base + "ano");
847 putIfMissing(namedArgs, "imperf1s", base + "avo");
848 putIfMissing(namedArgs, "imperf2s", base + "avi");
849 putIfMissing(namedArgs, "imperf3s", base + "ava");
850 putIfMissing(namedArgs, "imperf1p", base + "avamo");
851 putIfMissing(namedArgs, "imperf2p", base + "avate");
852 putIfMissing(namedArgs, "imperf3p", base + "avano");
854 putIfMissing(namedArgs, "prem1s", base + "ai");
855 putIfMissing(namedArgs, "prem2s", base + "asti");
856 putIfMissing(namedArgs, "prem3s", base + "ò");
857 putIfMissing(namedArgs, "prem1p", base + "ammo");
858 putIfMissing(namedArgs, "prem2p", base + "aste");
859 putIfMissing(namedArgs, "prem3p", base + "arono");
861 putIfMissing(namedArgs, "fut1s", base + "erò");
862 putIfMissing(namedArgs, "fut2s", base + "erai");
863 putIfMissing(namedArgs, "fut3s", base + "erà");
864 putIfMissing(namedArgs, "fut1p", base + "eremo");
865 putIfMissing(namedArgs, "fut2p", base + "erete");
866 putIfMissing(namedArgs, "fut3p", base + "eranno");
868 putIfMissing(namedArgs, "cond1s", base + "erei");
869 putIfMissing(namedArgs, "cond2s", base + "eresti");
870 putIfMissing(namedArgs, "cond3s", base + "erebbe");
871 putIfMissing(namedArgs, "cond1p", base + "eremmo");
872 putIfMissing(namedArgs, "cond2p", base + "ereste");
873 putIfMissing(namedArgs, "cond3p", base + "erebbero");
874 // Subjunctive / congiuntivo
875 putIfMissing(namedArgs, "sub123s", base + "i");
876 putIfMissing(namedArgs, "sub1p", base + "iamo");
877 putIfMissing(namedArgs, "sub2p", base + "iate");
878 putIfMissing(namedArgs, "sub3p", base + "ino");
879 // Imperfect subjunctive
880 putIfMissing(namedArgs, "impsub12s", base + "assi");
881 putIfMissing(namedArgs, "impsub3s", base + "asse");
882 putIfMissing(namedArgs, "impsub1p", base + "assimo");
883 putIfMissing(namedArgs, "impsub2p", base + "aste");
884 putIfMissing(namedArgs, "impsub3p", base + "assero");
886 putIfMissing(namedArgs, "imp2s", base + "a");
887 putIfMissing(namedArgs, "imp3s", base + "i");
888 putIfMissing(namedArgs, "imp1p", base + "iamo");
889 putIfMissing(namedArgs, "imp2p", base + "ate");
890 putIfMissing(namedArgs, "imp3p", base + "ino");
893 itConj(args, namedArgs);
897 private void itConj(List<String> args, Map<String, String> namedArgs) {
898 // TODO Auto-generated method stub
903 private static void putIfMissing(final Map<String, String> namedArgs, final String key,
904 final String value) {
905 final String oldValue = namedArgs.get(key);
906 if (oldValue == null || oldValue.length() == 0) {
907 namedArgs.put(key, value);
911 // TODO: check how ='' and =| are manifested....
912 // TODO: get this right in -are
913 private static void putOrNullify(final Map<String, String> namedArgs, final String key,
914 final String value) {
915 final String oldValue = namedArgs.get(key);
916 if (oldValue == null/* || oldValue.length() == 0*/) {
917 namedArgs.put(key, value);
919 if (oldValue.equals("''")) {
920 namedArgs.put(key, "");
925 static final Pattern whitespace = Pattern.compile("\\s+");
926 static String trim(final String s) {
927 return whitespace.matcher(s).replaceAll(" ").trim();