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 static final Logger LOG = Logger.getLogger(EnWiktionaryXmlParser.class.getName());
43 // TODO: process {{ttbc}} lines
45 static final Pattern partOfSpeechHeader = Pattern.compile(
46 "Noun|Verb|Adjective|Adverb|Pronoun|Conjunction|Interjection|" +
47 "Preposition|Proper noun|Article|Prepositional phrase|Acronym|" +
48 "Abbreviation|Initialism|Contraction|Prefix|Suffix|Symbol|Letter|" +
49 "Ligature|Idiom|Phrase|\\{\\{acronym\\}\\}|\\{\\{initialism\\}\\}|" +
50 // These are @deprecated:
51 "Noun form|Verb form|Adjective form|Nominal phrase|Noun phrase|" +
52 "Verb phrase|Transitive verb|Intransitive verb|Reflexive verb|" +
53 // These are extras I found:
54 "Determiner|Numeral|Number|Cardinal number|Ordinal number|Proverb|" +
55 "Particle|Interjection|Pronominal adverb" +
56 "Han character|Hanzi|Hanja|Kanji|Katakana character|Syllable");
58 final IndexBuilder enIndexBuilder;
59 final IndexBuilder otherIndexBuilder;
60 final Pattern langPattern;
61 final Pattern langCodePattern;
64 public EnWiktionaryXmlParser(final IndexBuilder enIndexBuilder, final IndexBuilder otherIndexBuilder, final Pattern langPattern, final Pattern langCodePattern, final boolean swap) {
65 this.enIndexBuilder = enIndexBuilder;
66 this.otherIndexBuilder = otherIndexBuilder;
67 this.langPattern = langPattern;
68 this.langCodePattern = langCodePattern;
73 public void parse(final File file, final int pageLimit) throws IOException {
75 final DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
77 if (pageLimit >= 0 && pageCount >= pageLimit) {
83 title = dis.readUTF();
84 } catch (EOFException e) {
88 final String heading = dis.readUTF();
89 final int bytesLength = dis.readInt();
90 final byte[] bytes = new byte[bytesLength];
92 final String text = new String(bytes, "UTF8");
94 parseSection(title, heading, text);
97 if (pageCount % 1000 == 0) {
98 LOG.info("pageCount=" + pageCount);
103 private void parseSection(final String title, String heading, final String text) {
104 if (title.startsWith("Wiktionary:") ||
105 title.startsWith("Template:") ||
106 title.startsWith("Appendix:") ||
107 title.startsWith("Category:") ||
108 title.startsWith("Index:") ||
109 title.startsWith("MediaWiki:") ||
110 title.startsWith("TransWiki:") ||
111 title.startsWith("Citations:") ||
112 title.startsWith("Concordance:") ||
113 title.startsWith("Help:")) {
117 heading = heading.replaceAll("=", "").trim();
118 if (heading.equals("English")) {
119 doEnglishWord(title, text);
120 } else if (langPattern.matcher(heading).matches()){
121 doForeignWord(title, text);
126 // -------------------------------------------------------------------------
128 private void doEnglishWord(String title, String text) {
133 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
134 while (wikiTokenizer.nextToken() != null) {
136 if (wikiTokenizer.isHeading()) {
137 final String headerName = wikiTokenizer.headingWikiText();
139 if (wikiTokenizer.headingDepth() <= posDepth) {
144 if (partOfSpeechHeader.matcher(headerName).matches()) {
145 posDepth = wikiTokenizer.headingDepth();
146 pos = wikiTokenizer.headingWikiText();
147 } else if (headerName.equals("Translations")) {
149 LOG.warning("Translations without POS: " + title);
151 doTranslations(title, wikiTokenizer, pos);
152 } else if (headerName.equals("Pronunciation")) {
153 //doPronunciation(wikiLineReader);
160 private static Set<String> encodings = new LinkedHashSet<String>(Arrays.asList("zh-ts",
161 "sd-Arab", "ku-Arab", "Arab", "unicode", "Laoo", "ur-Arab", "Thai",
162 "fa-Arab", "Khmr", "zh-tsp", "Cyrl", "IPAchar", "ug-Arab", "ko-inline",
163 "Jpan", "Kore", "Hebr", "rfscript", "Beng", "Mong", "Knda", "Cyrs",
164 "yue-tsj", "Mlym", "Tfng", "Grek", "yue-yue-j"));
166 private void doTranslations(final String title, final WikiTokenizer wikiTokenizer, final String pos) {
167 if (title.equals("absolutely")) {
168 //System.out.println();
171 String topLevelLang = null;
173 boolean done = false;
174 while (wikiTokenizer.nextToken() != null) {
175 if (wikiTokenizer.isHeading()) {
176 wikiTokenizer.returnToLineStart();
183 // Check whether we care about this line:
185 if (wikiTokenizer.isFunction()) {
186 final String functionName = wikiTokenizer.functionName();
187 final List<String> positionArgs = wikiTokenizer.functionPositionArgs();
189 if (functionName.equals("trans-top")) {
191 if (wikiTokenizer.functionPositionArgs().size() >= 1) {
192 sense = positionArgs.get(0);
193 // TODO: could emphasize words in [[brackets]] inside sense.
194 sense = WikiTokenizer.toPlainText(sense);
195 //LOG.info("Sense: " + sense);
197 } else if (functionName.equals("trans-bottom")) {
199 } else if (functionName.equals("trans-mid")) {
200 } else if (functionName.equals("trans-see")) {
201 // TODO: would also be nice...
202 } else if (functionName.startsWith("picdic")) {
203 } else if (functionName.startsWith("checktrans")) {
205 } else if (functionName.startsWith("ttbc")) {
206 wikiTokenizer.nextLine();
207 // TODO: would be great to handle ttbc
208 // TODO: Check this: done = true;
210 LOG.warning("Unexpected translation wikifunction: " + wikiTokenizer.token() + ", title=" + title);
212 } else if (wikiTokenizer.isListItem()) {
213 final String line = wikiTokenizer.listItemWikiText();
214 // This line could produce an output...
216 if (line.contains("ich hoan dich gear")) {
217 //System.out.println();
220 // First strip the language and check whether it matches.
221 // And hold onto it for sub-lines.
222 final int colonIndex = line.indexOf(":");
223 if (colonIndex == -1) {
227 final String lang = trim(WikiTokenizer.toPlainText(line.substring(0, colonIndex)));
228 final boolean appendLang;
229 if (wikiTokenizer.listItemPrefix().length() == 1) {
231 final boolean thisFind = langPattern.matcher(lang).find();
235 appendLang = !langPattern.matcher(lang).matches();
236 } else if (topLevelLang == null) {
239 // Two-level -- the only way we won't append is if this second level matches exactly.
240 if (!langPattern.matcher(lang).matches() && !langPattern.matcher(topLevelLang).find()) {
243 appendLang = !langPattern.matcher(lang).matches();
246 String rest = line.substring(colonIndex + 1).trim();
247 if (rest.length() > 0) {
248 doTranslationLine(line, appendLang ? lang : null, title, pos, sense, rest);
251 } else if (wikiTokenizer.remainderStartsWith("''See''")) {
252 wikiTokenizer.nextLine();
253 LOG.fine("Skipping line: " + wikiTokenizer.token());
254 } else if (wikiTokenizer.isWikiLink()) {
255 final String wikiLink = wikiTokenizer.wikiLinkText();
256 if (wikiLink.contains(":") && wikiLink.contains(title)) {
257 } else if (wikiLink.contains("Category:")) {
259 LOG.warning("Unexpected wikiLink: " + wikiTokenizer.token() + ", title=" + title);
261 } else if (wikiTokenizer.isNewline() || wikiTokenizer.isMarkup() || wikiTokenizer.isComment()) {
263 final String token = wikiTokenizer.token();
264 if (token.equals("----")) {
266 LOG.warning("Unexpected translation token: " + wikiTokenizer.token() + ", title=" + title);
273 private static <T> T get(final List<T> list, final int index) {
274 return index < list.size() ? list.get(index) : null;
277 private void doTranslationLine(final String line, final String lang, final String title, final String pos, final String sense, final String rest) {
278 // Good chance we'll actually file this one...
279 final PairEntry pairEntry = new PairEntry();
280 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
282 final StringBuilder otherText = new StringBuilder();
283 final WikiTokenizer wikiTokenizer = new WikiTokenizer(rest, false);
284 while (wikiTokenizer.nextToken() != null) {
286 if (wikiTokenizer.isPlainText()) {
287 final String plainText = wikiTokenizer.token();
288 otherText.append("").append(plainText);
289 otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
291 } else if (wikiTokenizer.isWikiLink()) {
292 final String plainText = wikiTokenizer.wikiLinkText();
293 otherText.append("").append(plainText);
294 otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_WIKI_TEXT);
296 } else if (wikiTokenizer.isFunction()) {
297 final String functionName = wikiTokenizer.functionName();
298 final List<String> args = wikiTokenizer.functionPositionArgs();
299 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
301 if (functionName.equals("t") || functionName.equals("t+") || functionName.equals("t-") || functionName.equals("tø") || functionName.equals("apdx-t")) {
302 if (args.size() < 2) {
303 LOG.warning("{{t}} with too few args: " + line + ", title=" + title);
306 final String langCode = get(args, 0);
307 //if (this.langCodePattern.matcher(langCode).matches()) {
308 final String word = get(args, 1);
309 final String gender = get(args, 2);
310 final String transliteration = namedArgs.get("tr");
311 if (otherText.length() > 0) {
312 otherText.append("");
314 otherText.append(word);
315 otherIndexBuilder.addEntryWithString(indexedEntry, word, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
316 if (gender != null) {
317 otherText.append(String.format(" {%s}", gender));
319 if (transliteration != null) {
320 otherText.append(String.format(" (tr. %s)", transliteration));
321 otherIndexBuilder.addEntryWithString(indexedEntry, transliteration, EntryTypeName.WIKTIONARY_TRANSLITERATION);
324 } else if (functionName.equals("qualifier")) {
325 if (args.size() == 0) {
326 otherText.append(wikiTokenizer.token());
328 String qualifier = args.get(0);
329 if (!namedArgs.isEmpty() || args.size() > 1) {
330 LOG.warning("weird qualifier: " + line);
333 otherText.append("(").append(qualifier).append(")");
335 } else if (encodings.contains(functionName)) {
336 otherText.append("").append(args.get(0));
337 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
338 } else if (isGender(functionName)) {
339 appendGender(otherText, functionName, args);
340 } else if (functionName.equals("g")) {
341 otherText.append("{g}");
342 } else if (functionName.equals("l")) {
343 // encodes text in various langs.
345 otherText.append("").append(args.get(1));
346 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(1), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
347 // TODO: transliteration
348 } else if (functionName.equals("term")) {
349 // cross-reference to another dictionary
350 otherText.append("").append(args.get(0));
351 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
352 // TODO: transliteration
353 } else if (functionName.equals("italbrac") || functionName.equals("gloss")) {
354 // TODO: put this text aside to use it.
355 otherText.append("[").append(args.get(0)).append("]");
356 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
357 } else if (functionName.equals("ttbc")) {
358 LOG.warning("Unexpected {{ttbc}}");
359 } else if (functionName.equals("trreq")) {
360 } else if (functionName.equals("not used")) {
361 otherText.append("(not used)");
362 } else if (functionName.equals("t-image")) {
363 // American sign language
366 otherText.append(wikiTokenizer.token());
369 } else if (wikiTokenizer.isNewline()) {
371 } else if (wikiTokenizer.isComment()) {
372 } else if (wikiTokenizer.isMarkup()) {
374 LOG.warning("Bad translation token: " + wikiTokenizer.token());
377 if (otherText.length() == 0) {
378 LOG.warning("Empty otherText: " + line);
383 otherText.insert(0, "(" + lang + ") ");
386 StringBuilder englishText = new StringBuilder();
388 englishText.append(title);
390 englishText.append(" (").append(sense).append(")");
391 enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
394 englishText.append(" (").append(pos.toLowerCase()).append(")");
396 enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
398 final Pair pair = new Pair(trim(englishText.toString()), trim(otherText.toString()), swap);
399 pairEntry.pairs.add(pair);
400 if (!pairsAdded.add(pair.toString())) {
401 LOG.warning("Duplicate pair: " + pair.toString());
403 if (pair.toString().equals("libero {m} :: free (adjective)")) {
404 System.out.println();
410 private void appendGender(final StringBuilder otherText,
411 final String functionName, final List<String> args) {
412 otherText.append("{");
413 otherText.append(functionName);
414 for (int i = 0; i < args.size(); ++i) {
415 otherText.append("|").append(args.get(i));
417 otherText.append("}");
421 private boolean isGender(final String functionName) {
422 return functionName.equals("m") || functionName.equals("f") || functionName.equals("n") || functionName.equals("p");
425 Set<String> pairsAdded = new LinkedHashSet<String>();
427 // -------------------------------------------------------------------------
429 private void doForeignWord(final String title, final String text) {
430 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
431 while (wikiTokenizer.nextToken() != null) {
432 if (wikiTokenizer.isHeading()) {
433 final String headingName = wikiTokenizer.headingWikiText();
434 if (headingName.equals("Translations")) {
435 LOG.warning("Translations not in English section: " + title);
436 } else if (headingName.equals("Pronunciation")) {
437 //doPronunciation(wikiLineReader);
438 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
439 doForeignPartOfSpeech(title, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
446 static final class ListSection {
447 final String firstPrefix;
448 final String firstLine;
449 final List<String> nextPrefixes = new ArrayList<String>();
450 final List<String> nextLines = new ArrayList<String>();
452 public ListSection(String firstPrefix, String firstLine) {
453 this.firstPrefix = firstPrefix;
454 this.firstLine = firstLine;
458 public String toString() {
459 return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
464 int foreignCount = 0;
465 private void doForeignPartOfSpeech(String title, final String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
466 if (++foreignCount % 1000 == 0) {
467 LOG.info("***" + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
469 if (title.equals("moro")) {
470 System.out.println();
473 final StringBuilder foreignBuilder = new StringBuilder();
474 final Collection<String> wordForms = new ArrayList<String>();
475 final List<ListSection> listSections = new ArrayList<ListSection>();
479 ListSection lastListSection = null;
481 int currentHeadingDepth = posDepth;
482 while (wikiTokenizer.nextToken() != null) {
483 if (wikiTokenizer.isHeading()) {
484 currentHeadingDepth = wikiTokenizer.headingDepth();
486 if (currentHeadingDepth <= posDepth) {
487 wikiTokenizer.returnToLineStart();
492 if (currentHeadingDepth > posDepth) {
493 // TODO: deal with other neat info sections
497 if (wikiTokenizer.isFunction()) {
498 final String name = wikiTokenizer.functionName();
499 final List<String> args = wikiTokenizer.functionPositionArgs();
500 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
501 // First line is generally a repeat of the title with some extra information.
502 // We need to build up the left side (foreign text, tokens) separately from the
503 // right side (English). The left-side may get paired with multiple right sides.
504 // The left side should get filed under every form of the word in question (singular, plural).
506 // For verbs, the conjugation comes later on in a deeper section.
507 // Ideally, we'd want to file every English entry with the verb
508 // under every verb form coming from the conjugation.
509 // Ie. under "fa": see: "make :: fare" and "do :: fare"
510 // But then where should we put the conjugation table?
511 // 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!)
512 // for the conjugation table from "fa".
513 // Would like to be able to link to a lang#token.
514 if (isGender(name)) {
515 appendGender(foreignBuilder, name, args);
516 } else if (name.equals("wikipedia")) {
517 namedArgs.remove("lang");
518 if (args.size() > 1 || !namedArgs.isEmpty()) {
520 foreignBuilder.append(wikiTokenizer.token());
521 } else if (args.size() == 1) {
522 foreignBuilder.append(wikiTokenizer.token());
524 //foreignBuilder.append(title);
526 } else if (name.equals("it-noun")) {
527 final String base = get(args, 0);
528 final String gender = get(args, 1);
529 final String singular = base + get(args, 2);
530 final String plural = base + get(args, 3);
531 foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
532 wordForms.add(singular);
533 wordForms.add(plural);
534 } else if (name.equals("it-proper noun")) {
535 foreignBuilder.append(wikiTokenizer.token());
536 } else if (name.equals("it-adj")) {
537 foreignBuilder.append(wikiTokenizer.token());
538 } else if (name.startsWith("it-conj")) {
539 if (name.equals("it-conj-are")) {
540 itConjAre(args, namedArgs);
541 } else if (name.equals("it-conj-ere")) {
542 } else if (name.equals("it-conj-ire")) {
544 LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
548 foreignBuilder.append(wikiTokenizer.token());
549 // LOG.warning("Unknown function: " + wikiTokenizer.token());
552 } else if (wikiTokenizer.isListItem()) {
553 final String prefix = wikiTokenizer.listItemPrefix();
554 if (lastListSection != null &&
555 prefix.startsWith(lastListSection.firstPrefix) &&
556 prefix.length() > lastListSection.firstPrefix.length()) {
557 lastListSection.nextPrefixes.add(prefix);
558 lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
560 lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
561 listSections.add(lastListSection);
563 } else if (lastListSection != null) {
564 // Don't append anything after the lists, because there's crap.
565 } else if (wikiTokenizer.isWikiLink()) {
567 foreignBuilder.append(wikiTokenizer.wikiLinkText());
569 } else if (wikiTokenizer.isPlainText()) {
571 foreignBuilder.append(wikiTokenizer.token());
573 } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
576 LOG.warning("Unexpected token: " + wikiTokenizer.token());
581 // Here's where we exit.
582 // Should we make an entry even if there are no foreign list items?
583 String foreign = foreignBuilder.toString().trim();
584 if (!foreign.toLowerCase().startsWith(title.toLowerCase())) {
585 foreign = title + " " + foreign;
587 for (final ListSection listSection : listSections) {
588 doForeignListItem(foreign, title, wordForms, listSection);
594 static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
595 "(first|second|third)-person (singular|plural)|" +
601 private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
603 final String prefix = listSection.firstPrefix;
604 if (prefix.length() > 1) {
605 // Could just get looser and say that any prefix longer than first is a sublist.
606 LOG.warning("Prefix too long: " + listSection);
610 final PairEntry pairEntry = new PairEntry();
611 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
613 final StringBuilder englishBuilder = new StringBuilder();
615 final String mainLine = listSection.firstLine;
617 final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
618 while (englishTokenizer.nextToken() != null) {
619 // TODO handle form of....
620 if (englishTokenizer.isPlainText()) {
621 englishBuilder.append(englishTokenizer.token());
622 enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
623 } else if (englishTokenizer.isWikiLink()) {
624 final String text = englishTokenizer.wikiLinkText();
625 final String link = englishTokenizer.wikiLinkDest();
627 if (link.contains("#English")) {
628 englishBuilder.append(text);
629 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
630 } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
631 englishBuilder.append(text);
632 otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
633 } else if (link.equals("plural")) {
634 englishBuilder.append(text);
636 //LOG.warning("Special link: " + englishTokenizer.token());
637 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
638 englishBuilder.append(text);
642 englishBuilder.append(text);
643 if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
644 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
647 } else if (englishTokenizer.isFunction()) {
648 final String name = englishTokenizer.functionName();
649 if (name.contains("conjugation of ") ||
650 name.contains("form of ") ||
651 name.contains("feminine of ") ||
652 name.contains("plural of ")) {
653 // Ignore these in the index, they're really annoying....
654 englishBuilder.append(englishTokenizer.token());
656 englishBuilder.append(englishTokenizer.token());
657 // LOG.warning("Unexpected function: " + englishTokenizer.token());
660 if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
662 LOG.warning("Unexpected definition text: " + englishTokenizer.token());
667 final String english = trim(englishBuilder.toString());
668 if (english.length() > 0) {
669 final Pair pair = new Pair(english, trim(foreignText), this.swap);
670 pairEntry.pairs.add(pair);
671 otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
672 for (final String form : forms) {
673 otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_FORM_SINGLE, EntryTypeName.WIKTIONARY_FORM_MULTI);
678 String lastForeign = null;
679 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
680 final String nextPrefix = listSection.nextPrefixes.get(i);
681 final String nextLine = listSection.nextLines.get(i);
682 int dash = nextLine.indexOf("—");
685 dash = nextLine.indexOf("—");
689 dash = nextLine.indexOf(" - ");
693 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
694 final String foreignEx = nextLine.substring(0, dash);
695 final String englishEx = nextLine.substring(dash + mdashLen);
696 final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
697 if (pair.lang1 != "--" && pair.lang1 != "--") {
698 pairEntry.pairs.add(pair);
701 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
702 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
703 lastForeign = nextLine;
704 if (pair.lang1 != "--" && pair.lang1 != "--") {
705 pairEntry.pairs.add(pair);
707 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
708 if (lastForeign != null && pairEntry.pairs.size() > 0) {
709 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
710 final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
711 if (pair.lang1 != "--" && pair.lang1 != "--") {
712 pairEntry.pairs.add(pair);
716 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
717 // TODO: add something.
719 } else if (nextPrefix.equals("#*")) {
720 // Can't really index these.
721 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
722 lastForeign = nextLine;
723 if (pair.lang1 != "--" && pair.lang1 != "--") {
724 pairEntry.pairs.add(pair);
726 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
727 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
728 if (pair.lang1 != "--" && pair.lang1 != "--") {
729 pairEntry.pairs.add(pair);
737 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
738 final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
739 final StringBuilder builder = new StringBuilder();
740 boolean insideTripleQuotes = false;
741 while (wikiTokenizer.nextToken() != null) {
742 if (wikiTokenizer.isPlainText()) {
743 builder.append(wikiTokenizer.token());
744 if (indexBuilder != null) {
745 indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
747 } else if (wikiTokenizer.isWikiLink()) {
748 final String text = wikiTokenizer.wikiLinkText().replaceAll("'", "");
749 builder.append(text);
750 if (indexBuilder != null) {
751 indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
753 } else if (wikiTokenizer.isFunction()) {
754 builder.append(wikiTokenizer.token());
755 } else if (wikiTokenizer.isMarkup()) {
756 if (wikiTokenizer.token().equals("'''")) {
757 insideTripleQuotes = !insideTripleQuotes;
759 } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
762 LOG.warning("unexpected token: " + wikiTokenizer.token());
765 final String result = trim(builder.toString());
766 return result.length() > 0 ? result : "--";
770 private void itConjAre(List<String> args, Map<String, String> namedArgs) {
771 final String base = args.get(0);
772 final String aux = args.get(1);
774 putIfMissing(namedArgs, "inf", base + "are");
775 putIfMissing(namedArgs, "aux", aux);
776 putIfMissing(namedArgs, "ger", base + "ando");
777 putIfMissing(namedArgs, "presp", base + "ante");
778 putIfMissing(namedArgs, "pastp", base + "ato");
780 putIfMissing(namedArgs, "pres1s", base + "o");
781 putIfMissing(namedArgs, "pres2s", base + "i");
782 putIfMissing(namedArgs, "pres3s", base + "a");
783 putIfMissing(namedArgs, "pres1p", base + "iamo");
784 putIfMissing(namedArgs, "pres2p", base + "ate");
785 putIfMissing(namedArgs, "pres3p", base + "ano");
787 putIfMissing(namedArgs, "imperf1s", base + "avo");
788 putIfMissing(namedArgs, "imperf2s", base + "avi");
789 putIfMissing(namedArgs, "imperf3s", base + "ava");
790 putIfMissing(namedArgs, "imperf1p", base + "avamo");
791 putIfMissing(namedArgs, "imperf2p", base + "avate");
792 putIfMissing(namedArgs, "imperf3p", base + "avano");
794 putIfMissing(namedArgs, "prem1s", base + "ai");
795 putIfMissing(namedArgs, "prem2s", base + "asti");
796 putIfMissing(namedArgs, "prem3s", base + "ò");
797 putIfMissing(namedArgs, "prem1p", base + "ammo");
798 putIfMissing(namedArgs, "prem2p", base + "aste");
799 putIfMissing(namedArgs, "prem3p", base + "arono");
801 putIfMissing(namedArgs, "fut1s", base + "erò");
802 putIfMissing(namedArgs, "fut2s", base + "erai");
803 putIfMissing(namedArgs, "fut3s", base + "erà");
804 putIfMissing(namedArgs, "fut1p", base + "eremo");
805 putIfMissing(namedArgs, "fut2p", base + "erete");
806 putIfMissing(namedArgs, "fut3p", base + "eranno");
808 putIfMissing(namedArgs, "cond1s", base + "erei");
809 putIfMissing(namedArgs, "cond2s", base + "eresti");
810 putIfMissing(namedArgs, "cond3s", base + "erebbe");
811 putIfMissing(namedArgs, "cond1p", base + "eremmo");
812 putIfMissing(namedArgs, "cond2p", base + "ereste");
813 putIfMissing(namedArgs, "cond3p", base + "erebbero");
814 // Subjunctive / congiuntivo
815 putIfMissing(namedArgs, "sub123s", base + "i");
816 putIfMissing(namedArgs, "sub1p", base + "iamo");
817 putIfMissing(namedArgs, "sub2p", base + "iate");
818 putIfMissing(namedArgs, "sub3p", base + "ino");
819 // Imperfect subjunctive
820 putIfMissing(namedArgs, "impsub12s", base + "assi");
821 putIfMissing(namedArgs, "impsub3s", base + "asse");
822 putIfMissing(namedArgs, "impsub1p", base + "assimo");
823 putIfMissing(namedArgs, "impsub2p", base + "aste");
824 putIfMissing(namedArgs, "impsub3p", base + "assero");
826 putIfMissing(namedArgs, "imp2s", base + "a");
827 putIfMissing(namedArgs, "imp3s", base + "i");
828 putIfMissing(namedArgs, "imp1p", base + "iamo");
829 putIfMissing(namedArgs, "imp2p", base + "ate");
830 putIfMissing(namedArgs, "imp3p", base + "ino");
833 itConj(args, namedArgs);
837 private void itConj(List<String> args, Map<String, String> namedArgs) {
838 // TODO Auto-generated method stub
843 private static void putIfMissing(final Map<String, String> namedArgs, final String key,
844 final String value) {
845 final String oldValue = namedArgs.get(key);
846 if (oldValue == null || oldValue.length() == 0) {
847 namedArgs.put(key, value);
851 // TODO: check how ='' and =| are manifested....
852 // TODO: get this right in -are
853 private static void putOrNullify(final Map<String, String> namedArgs, final String key,
854 final String value) {
855 final String oldValue = namedArgs.get(key);
856 if (oldValue == null/* || oldValue.length() == 0*/) {
857 namedArgs.put(key, value);
859 if (oldValue.equals("''")) {
860 namedArgs.put(key, "");
865 static final Pattern whitespace = Pattern.compile("\\s+");
866 static String trim(final String s) {
867 return whitespace.matcher(s).replaceAll(" ").trim();