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, final T defaultValue) {
278 return index < list.size() ? list.get(index) : defaultValue;
281 private static <T> T get(final List<T> list, final int index) {
282 return get(list, index, null);
285 private static <T> T remove(final List<T> list, final int index, final T defaultValue) {
286 return index < list.size() ? list.remove(index) : defaultValue;
289 private void doTranslationLine(final String line, final String lang, final String title, final String pos, final String sense, final String rest) {
290 // Good chance we'll actually file this one...
291 final PairEntry pairEntry = new PairEntry();
292 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
294 final StringBuilder otherText = new StringBuilder();
295 final WikiTokenizer wikiTokenizer = new WikiTokenizer(rest, false);
296 while (wikiTokenizer.nextToken() != null) {
298 if (wikiTokenizer.isPlainText()) {
299 final String plainText = wikiTokenizer.token();
300 otherText.append("").append(plainText);
301 otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
303 } else if (wikiTokenizer.isWikiLink()) {
304 final String plainText = wikiTokenizer.wikiLinkText();
305 otherText.append("").append(plainText);
306 otherIndexBuilder.addEntryWithString(indexedEntry, plainText, EntryTypeName.WIKTIONARY_TRANSLATION_WIKI_TEXT);
308 } else if (wikiTokenizer.isFunction()) {
309 final String functionName = wikiTokenizer.functionName();
310 final List<String> args = wikiTokenizer.functionPositionArgs();
311 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
313 if (functionName.equals("t") || functionName.equals("t+") || functionName.equals("t-") || functionName.equals("tø") || functionName.equals("apdx-t")) {
314 if (args.size() < 2) {
315 LOG.warning("{{t}} with too few args: " + line + ", title=" + title);
318 final String langCode = get(args, 0);
319 //if (this.langCodePattern.matcher(langCode).matches()) {
320 final String word = get(args, 1);
321 final String gender = get(args, 2);
322 final String transliteration = namedArgs.get("tr");
323 if (otherText.length() > 0) {
324 otherText.append("");
326 otherText.append(word);
327 otherIndexBuilder.addEntryWithString(indexedEntry, word, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
328 if (gender != null) {
329 otherText.append(String.format(" {%s}", gender));
331 if (transliteration != null) {
332 otherText.append(String.format(TRANSLITERATION_FORMAT, transliteration));
333 otherIndexBuilder.addEntryWithString(indexedEntry, transliteration, EntryTypeName.WIKTIONARY_TRANSLITERATION);
336 } else if (functionName.equals("qualifier")) {
337 if (args.size() == 0) {
338 otherText.append(wikiTokenizer.token());
340 String qualifier = args.get(0);
341 if (!namedArgs.isEmpty() || args.size() > 1) {
342 LOG.warning("weird qualifier: " + line);
345 otherText.append("(").append(qualifier).append(")");
347 } else if (encodings.contains(functionName)) {
348 otherText.append("").append(args.get(0));
349 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
350 } else if (isGender(functionName)) {
351 appendGender(otherText, functionName, args);
352 } else if (functionName.equals("g")) {
353 otherText.append("{g}");
354 } else if (functionName.equals("l")) {
355 // encodes text in various langs.
357 otherText.append("").append(args.get(1));
358 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(1), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
359 // TODO: transliteration
360 } else if (functionName.equals("term")) {
361 // cross-reference to another dictionary
362 otherText.append("").append(args.get(0));
363 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
364 // TODO: transliteration
365 } else if (functionName.equals("italbrac") || functionName.equals("gloss")) {
366 // TODO: put this text aside to use it.
367 otherText.append("[").append(args.get(0)).append("]");
368 otherIndexBuilder.addEntryWithString(indexedEntry, args.get(0), EntryTypeName.WIKTIONARY_TRANSLATION_OTHER_TEXT);
369 } else if (functionName.equals("ttbc")) {
370 LOG.warning("Unexpected {{ttbc}}");
371 } else if (functionName.equals("trreq")) {
372 } else if (functionName.equals("not used")) {
373 otherText.append("(not used)");
374 } else if (functionName.equals("t-image")) {
375 // American sign language
378 namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
379 WikiTokenizer.appendFunction(otherText.append("{{"), functionName, args, namedArgs).append("}}");
382 } else if (wikiTokenizer.isNewline()) {
384 } else if (wikiTokenizer.isComment()) {
385 } else if (wikiTokenizer.isMarkup()) {
387 LOG.warning("Bad translation token: " + wikiTokenizer.token());
390 if (otherText.length() == 0) {
391 LOG.warning("Empty otherText: " + line);
396 otherText.insert(0, String.format("(%s) ", lang));
399 StringBuilder englishText = new StringBuilder();
401 englishText.append(title);
403 englishText.append(" (").append(sense).append(")");
404 enIndexBuilder.addEntryWithString(indexedEntry, sense, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE, EntryTypeName.WIKTIONARY_TRANSLATION_SENSE);
407 englishText.append(" (").append(pos.toLowerCase()).append(")");
409 enIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
411 final Pair pair = new Pair(trim(englishText.toString()), trim(otherText.toString()), swap);
412 pairEntry.pairs.add(pair);
413 if (!pairsAdded.add(pair.toString())) {
414 LOG.warning("Duplicate pair: " + pair.toString());
416 if (pair.toString().equals("libero {m} :: free (adjective)")) {
417 System.out.println();
423 private void appendGender(final StringBuilder otherText,
424 final String functionName, final List<String> args) {
425 otherText.append("{");
426 otherText.append(functionName);
427 for (int i = 0; i < args.size(); ++i) {
428 otherText.append("|").append(args.get(i));
430 otherText.append("}");
434 private boolean isGender(final String functionName) {
435 return functionName.equals("m") || functionName.equals("f") || functionName.equals("n") || functionName.equals("p");
438 Set<String> pairsAdded = new LinkedHashSet<String>();
440 // -------------------------------------------------------------------------
442 private void doForeignWord(final String lang, final String title, final String text) {
443 final WikiTokenizer wikiTokenizer = new WikiTokenizer(text);
444 while (wikiTokenizer.nextToken() != null) {
445 if (wikiTokenizer.isHeading()) {
446 final String headingName = wikiTokenizer.headingWikiText();
447 if (headingName.equals("Translations")) {
448 LOG.warning("Translations not in English section: " + title);
449 } else if (headingName.equals("Pronunciation")) {
450 //doPronunciation(wikiLineReader);
451 } else if (partOfSpeechHeader.matcher(headingName).matches()) {
452 doForeignPartOfSpeech(lang, title, headingName, wikiTokenizer.headingDepth(), wikiTokenizer);
459 static final class ListSection {
460 final String firstPrefix;
461 final String firstLine;
462 final List<String> nextPrefixes = new ArrayList<String>();
463 final List<String> nextLines = new ArrayList<String>();
465 public ListSection(String firstPrefix, String firstLine) {
466 this.firstPrefix = firstPrefix;
467 this.firstLine = firstLine;
471 public String toString() {
472 return firstPrefix + firstLine + "{ " + nextPrefixes + "}";
477 int foreignCount = 0;
478 private void doForeignPartOfSpeech(final String lang, String title, final String posHeading, final int posDepth, WikiTokenizer wikiTokenizer) {
479 if (++foreignCount % 1000 == 0) {
480 LOG.info("***" + lang + ", " + title + ", pos=" + posHeading + ", foreignCount=" + foreignCount);
482 if (title.equals("moro")) {
483 System.out.println();
486 boolean titleAppended = false;
487 final StringBuilder foreignBuilder = new StringBuilder();
488 final Collection<String> wordForms = new ArrayList<String>();
489 final List<ListSection> listSections = new ArrayList<ListSection>();
493 ListSection lastListSection = null;
495 int currentHeadingDepth = posDepth;
496 while (wikiTokenizer.nextToken() != null) {
497 if (wikiTokenizer.isHeading()) {
498 currentHeadingDepth = wikiTokenizer.headingDepth();
500 if (currentHeadingDepth <= posDepth) {
501 wikiTokenizer.returnToLineStart();
506 if (currentHeadingDepth > posDepth) {
507 // TODO: deal with other neat info sections
511 if (wikiTokenizer.isFunction()) {
512 final String name = wikiTokenizer.functionName();
513 final List<String> args = wikiTokenizer.functionPositionArgs();
514 final Map<String,String> namedArgs = wikiTokenizer.functionNamedArgs();
515 // First line is generally a repeat of the title with some extra information.
516 // We need to build up the left side (foreign text, tokens) separately from the
517 // right side (English). The left-side may get paired with multiple right sides.
518 // The left side should get filed under every form of the word in question (singular, plural).
520 // For verbs, the conjugation comes later on in a deeper section.
521 // Ideally, we'd want to file every English entry with the verb
522 // under every verb form coming from the conjugation.
523 // Ie. under "fa": see: "make :: fare" and "do :: fare"
524 // But then where should we put the conjugation table?
525 // 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!)
526 // for the conjugation table from "fa".
527 // Would like to be able to link to a lang#token.
528 if (isGender(name)) {
529 appendGender(foreignBuilder, name, args);
530 } else if (name.equals("wikipedia")) {
531 namedArgs.remove("lang");
532 if (args.size() > 1 || !namedArgs.isEmpty()) {
534 foreignBuilder.append(wikiTokenizer.token());
535 } else if (args.size() == 1) {
536 foreignBuilder.append(wikiTokenizer.token());
538 //foreignBuilder.append(title);
540 } else if (name.equals("attention") || name.equals("zh-attention")) {
541 // See: http://en.wiktionary.org/wiki/Template:attention
543 } else if (name.equals("infl")) {
544 // See: http://en.wiktionary.org/wiki/Template:infl
545 final String langCode = get(args, 0);
546 String head = namedArgs.remove("head");
548 head = namedArgs.remove("title"); // Bug
553 head = WikiTokenizer.toPlainText(head);
555 titleAppended = true;
557 namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
559 final String tr = namedArgs.remove("tr");
560 String g = namedArgs.remove("g");
562 g = namedArgs.remove("gender");
564 final String g2 = namedArgs.remove("g2");
565 final String g3 = namedArgs.remove("g3");
567 foreignBuilder.append(head);
570 foreignBuilder.append(" {").append(g);
572 foreignBuilder.append("|").append(g2);
575 foreignBuilder.append("|").append(g3);
577 foreignBuilder.append("}");
581 foreignBuilder.append(String.format(TRANSLITERATION_FORMAT, tr));
585 final String pos = get(args, 1);
587 foreignBuilder.append(" (").append(pos).append(")");
589 for (int i = 2; i < args.size(); i += 2) {
590 final String inflName = get(args, i);
591 final String inflValue = get(args, i + 1);
592 foreignBuilder.append(", ").append(WikiTokenizer.toPlainText(inflName));
593 if (inflValue != null && inflValue.length() > 0) {
594 foreignBuilder.append(": ").append(WikiTokenizer.toPlainText(inflValue));
595 wordForms.add(inflValue);
598 for (final String key : namedArgs.keySet()) {
599 final String value = WikiTokenizer.toPlainText(namedArgs.get(key));
600 foreignBuilder.append(" ").append(key).append("=").append(value);
601 wordForms.add(value);
603 } else if (name.equals("it-noun")) {
604 titleAppended = true;
605 final String base = get(args, 0);
606 final String gender = get(args, 1);
607 final String singular = base + get(args, 2);
608 final String plural = base + get(args, 3);
609 foreignBuilder.append(String.format(" %s {%s}, %s {pl}", singular, gender, plural, plural));
610 wordForms.add(singular);
611 wordForms.add(plural);
612 if (!namedArgs.isEmpty() || args.size() > 4) {
613 LOG.warning("Invalid it-noun: " + wikiTokenizer.token());
615 } else if (name.equals("it-proper noun")) {
616 foreignBuilder.append(wikiTokenizer.token());
617 } else if (name.equals("it-adj")) {
618 foreignBuilder.append(wikiTokenizer.token());
619 } else if (name.startsWith("it-conj")) {
620 if (name.equals("it-conj-are")) {
621 itConjAre(args, namedArgs);
622 } else if (name.equals("it-conj-ere")) {
623 } else if (name.equals("it-conj-ire")) {
625 LOG.warning("Unknown conjugation: " + wikiTokenizer.token());
629 foreignBuilder.append(wikiTokenizer.token());
630 // LOG.warning("Unknown function: " + wikiTokenizer.token());
632 } else if (wikiTokenizer.isListItem()) {
633 final String prefix = wikiTokenizer.listItemPrefix();
634 if (lastListSection != null &&
635 prefix.startsWith(lastListSection.firstPrefix) &&
636 prefix.length() > lastListSection.firstPrefix.length()) {
637 lastListSection.nextPrefixes.add(prefix);
638 lastListSection.nextLines.add(wikiTokenizer.listItemWikiText());
640 lastListSection = new ListSection(prefix, wikiTokenizer.listItemWikiText());
641 listSections.add(lastListSection);
643 } else if (lastListSection != null) {
644 // Don't append anything after the lists, because there's crap.
645 } else if (wikiTokenizer.isWikiLink()) {
647 foreignBuilder.append(wikiTokenizer.wikiLinkText());
649 } else if (wikiTokenizer.isPlainText()) {
651 foreignBuilder.append(wikiTokenizer.token());
653 } else if (wikiTokenizer.isMarkup() || wikiTokenizer.isNewline() || wikiTokenizer.isComment()) {
656 LOG.warning("Unexpected token: " + wikiTokenizer.token());
661 // Here's where we exit.
662 // Should we make an entry even if there are no foreign list items?
663 String foreign = foreignBuilder.toString().trim();
664 if (!titleAppended && !foreign.toLowerCase().startsWith(title.toLowerCase())) {
665 foreign = String.format("%s %s", title, foreign);
667 if (!langPattern.matcher(lang).matches()) {
668 foreign = String.format("(%s) %s", lang, foreign);
670 for (final ListSection listSection : listSections) {
671 doForeignListItem(foreign, title, wordForms, listSection);
677 static final Pattern UNINDEXED_WIKI_TEXT = Pattern.compile(
678 "(first|second|third)-person (singular|plural)|" +
683 // Might only want to remove "lang" if it's equal to "zh", for example.
684 static final Set<String> USELESS_WIKI_ARGS = new LinkedHashSet<String>(Arrays.asList("lang", "sc", "sort", "cat"));
686 private void doForeignListItem(final String foreignText, String title, final Collection<String> forms, final ListSection listSection) {
688 final String prefix = listSection.firstPrefix;
689 if (prefix.length() > 1) {
690 // Could just get looser and say that any prefix longer than first is a sublist.
691 LOG.warning("Prefix too long: " + listSection);
695 final PairEntry pairEntry = new PairEntry();
696 final IndexedEntry indexedEntry = new IndexedEntry(pairEntry);
698 final StringBuilder englishBuilder = new StringBuilder();
700 final String mainLine = listSection.firstLine;
701 final WikiTokenizer englishTokenizer = new WikiTokenizer(mainLine, false);
702 while (englishTokenizer.nextToken() != null) {
703 // TODO handle form of....
704 if (englishTokenizer.isPlainText()) {
705 englishBuilder.append(englishTokenizer.token());
706 enIndexBuilder.addEntryWithString(indexedEntry, englishTokenizer.token(), EntryTypeName.WIKTIONARY_ENGLISH_DEF);
707 } else if (englishTokenizer.isWikiLink()) {
708 final String text = englishTokenizer.wikiLinkText();
709 final String link = englishTokenizer.wikiLinkDest();
711 if (link.contains("#English")) {
712 englishBuilder.append(text);
713 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
714 } else if (link.contains("#") && this.langPattern.matcher(link).find()) {
715 englishBuilder.append(text);
716 otherIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_OTHER_LANG);
717 } else if (link.equals("plural")) {
718 englishBuilder.append(text);
720 //LOG.warning("Special link: " + englishTokenizer.token());
721 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
722 englishBuilder.append(text);
726 englishBuilder.append(text);
727 if (!UNINDEXED_WIKI_TEXT.matcher(text).find()) {
728 enIndexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_ENGLISH_DEF_WIKI_LINK);
731 } else if (englishTokenizer.isFunction()) {
732 final String name = englishTokenizer.functionName();
733 final List<String> args = englishTokenizer.functionPositionArgs();
734 final Map<String,String> namedArgs = englishTokenizer.functionNamedArgs();
737 name.equals("form of") ||
738 name.contains("conjugation of") ||
739 name.contains("participle of") ||
740 name.contains("gerund of") ||
741 name.contains("feminine of") ||
742 name.contains("plural of")) {
743 String formName = name;
744 if (name.equals("form of")) {
745 formName = args.remove(0);
747 String baseForm = get(args, 1, "");
748 if ("".equals(baseForm)) {
749 baseForm = get(args, 0, null);
752 remove(args, 0, null);
754 namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
755 WikiTokenizer.appendFunction(englishBuilder.append("{"), formName, args, namedArgs).append("}");
756 otherIndexBuilder.addEntryWithString(indexedEntry, baseForm, EntryTypeName.WIKTIONARY_BASE_FORM_SINGLE, EntryTypeName.WIKTIONARY_BASE_FORM_MULTI);
759 namedArgs.keySet().removeAll(USELESS_WIKI_ARGS);
760 WikiTokenizer.appendFunction(englishBuilder.append("{{"), name, args, namedArgs).append("}}");
761 // LOG.warning("Unexpected function: " + englishTokenizer.token());
764 if (englishTokenizer.isComment() || englishTokenizer.isMarkup()) {
766 LOG.warning("Unexpected definition type: " + englishTokenizer.token());
771 final String english = trim(englishBuilder.toString());
772 if (english.length() > 0) {
773 final Pair pair = new Pair(english, trim(foreignText), this.swap);
774 pairEntry.pairs.add(pair);
775 otherIndexBuilder.addEntryWithString(indexedEntry, title, EntryTypeName.WIKTIONARY_TITLE_SINGLE, EntryTypeName.WIKTIONARY_TITLE_MULTI);
776 for (final String form : forms) {
777 otherIndexBuilder.addEntryWithString(indexedEntry, form, EntryTypeName.WIKTIONARY_INFLECTD_FORM_SINGLE, EntryTypeName.WIKTIONARY_INFLECTED_FORM_MULTI);
782 String lastForeign = null;
783 for (int i = 0; i < listSection.nextPrefixes.size(); ++i) {
784 final String nextPrefix = listSection.nextPrefixes.get(i);
785 final String nextLine = listSection.nextLines.get(i);
786 int dash = nextLine.indexOf("—");
789 dash = nextLine.indexOf("—");
793 dash = nextLine.indexOf(" - ");
797 if ((nextPrefix.equals("#:") || nextPrefix.equals("##:")) && dash != -1) {
798 final String foreignEx = nextLine.substring(0, dash);
799 final String englishEx = nextLine.substring(dash + mdashLen);
800 final Pair pair = new Pair(formatAndIndexExampleString(englishEx, enIndexBuilder, indexedEntry), formatAndIndexExampleString(foreignEx, otherIndexBuilder, indexedEntry), swap);
801 if (pair.lang1 != "--" && pair.lang1 != "--") {
802 pairEntry.pairs.add(pair);
805 } else if (nextPrefix.equals("#:") || nextPrefix.equals("##:")){
806 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
807 lastForeign = nextLine;
808 if (pair.lang1 != "--" && pair.lang1 != "--") {
809 pairEntry.pairs.add(pair);
811 } else if (nextPrefix.equals("#::") || nextPrefix.equals("#**")) {
812 if (lastForeign != null && pairEntry.pairs.size() > 0) {
813 pairEntry.pairs.remove(pairEntry.pairs.size() - 1);
814 final Pair pair = new Pair(formatAndIndexExampleString(nextLine, enIndexBuilder, indexedEntry), formatAndIndexExampleString(lastForeign, otherIndexBuilder, indexedEntry), swap);
815 if (pair.lang1 != "--" || pair.lang2 != "--") {
816 pairEntry.pairs.add(pair);
820 LOG.warning("TODO: English example with no foreign: " + title + ", " + nextLine);
821 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
822 if (pair.lang1 != "--" || pair.lang2 != "--") {
823 pairEntry.pairs.add(pair);
826 } else if (nextPrefix.equals("#*")) {
827 // Can't really index these.
828 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
829 lastForeign = nextLine;
830 if (pair.lang1 != "--" || pair.lang2 != "--") {
831 pairEntry.pairs.add(pair);
833 } else if (nextPrefix.equals("#::*") || nextPrefix.equals("##") || nextPrefix.equals("#*:") || nextPrefix.equals("#:*") || true) {
834 final Pair pair = new Pair("--", formatAndIndexExampleString(nextLine, null, indexedEntry), swap);
835 if (pair.lang1 != "--" || pair.lang2 != "--") {
836 pairEntry.pairs.add(pair);
844 private String formatAndIndexExampleString(final String example, final IndexBuilder indexBuilder, final IndexedEntry indexedEntry) {
845 final WikiTokenizer wikiTokenizer = new WikiTokenizer(example, false);
846 final StringBuilder builder = new StringBuilder();
847 boolean insideTripleQuotes = false;
848 while (wikiTokenizer.nextToken() != null) {
849 if (wikiTokenizer.isPlainText()) {
850 builder.append(wikiTokenizer.token());
851 if (indexBuilder != null) {
852 indexBuilder.addEntryWithString(indexedEntry, wikiTokenizer.token(), EntryTypeName.WIKTIONARY_EXAMPLE);
854 } else if (wikiTokenizer.isWikiLink()) {
855 final String text = wikiTokenizer.wikiLinkText().replaceAll("'", "");
856 builder.append(text);
857 if (indexBuilder != null) {
858 indexBuilder.addEntryWithString(indexedEntry, text, EntryTypeName.WIKTIONARY_EXAMPLE);
860 } else if (wikiTokenizer.isFunction()) {
861 builder.append(wikiTokenizer.token());
862 } else if (wikiTokenizer.isMarkup()) {
863 if (wikiTokenizer.token().equals("'''")) {
864 insideTripleQuotes = !insideTripleQuotes;
866 } else if (wikiTokenizer.isComment() || wikiTokenizer.isNewline()) {
869 LOG.warning("unexpected token: " + wikiTokenizer.token());
872 final String result = trim(builder.toString());
873 return result.length() > 0 ? result : "--";
877 private void itConjAre(List<String> args, Map<String, String> namedArgs) {
878 final String base = args.get(0);
879 final String aux = args.get(1);
881 putIfMissing(namedArgs, "inf", base + "are");
882 putIfMissing(namedArgs, "aux", aux);
883 putIfMissing(namedArgs, "ger", base + "ando");
884 putIfMissing(namedArgs, "presp", base + "ante");
885 putIfMissing(namedArgs, "pastp", base + "ato");
887 putIfMissing(namedArgs, "pres1s", base + "o");
888 putIfMissing(namedArgs, "pres2s", base + "i");
889 putIfMissing(namedArgs, "pres3s", base + "a");
890 putIfMissing(namedArgs, "pres1p", base + "iamo");
891 putIfMissing(namedArgs, "pres2p", base + "ate");
892 putIfMissing(namedArgs, "pres3p", base + "ano");
894 putIfMissing(namedArgs, "imperf1s", base + "avo");
895 putIfMissing(namedArgs, "imperf2s", base + "avi");
896 putIfMissing(namedArgs, "imperf3s", base + "ava");
897 putIfMissing(namedArgs, "imperf1p", base + "avamo");
898 putIfMissing(namedArgs, "imperf2p", base + "avate");
899 putIfMissing(namedArgs, "imperf3p", base + "avano");
901 putIfMissing(namedArgs, "prem1s", base + "ai");
902 putIfMissing(namedArgs, "prem2s", base + "asti");
903 putIfMissing(namedArgs, "prem3s", base + "ò");
904 putIfMissing(namedArgs, "prem1p", base + "ammo");
905 putIfMissing(namedArgs, "prem2p", base + "aste");
906 putIfMissing(namedArgs, "prem3p", base + "arono");
908 putIfMissing(namedArgs, "fut1s", base + "erò");
909 putIfMissing(namedArgs, "fut2s", base + "erai");
910 putIfMissing(namedArgs, "fut3s", base + "erà");
911 putIfMissing(namedArgs, "fut1p", base + "eremo");
912 putIfMissing(namedArgs, "fut2p", base + "erete");
913 putIfMissing(namedArgs, "fut3p", base + "eranno");
915 putIfMissing(namedArgs, "cond1s", base + "erei");
916 putIfMissing(namedArgs, "cond2s", base + "eresti");
917 putIfMissing(namedArgs, "cond3s", base + "erebbe");
918 putIfMissing(namedArgs, "cond1p", base + "eremmo");
919 putIfMissing(namedArgs, "cond2p", base + "ereste");
920 putIfMissing(namedArgs, "cond3p", base + "erebbero");
921 // Subjunctive / congiuntivo
922 putIfMissing(namedArgs, "sub123s", base + "i");
923 putIfMissing(namedArgs, "sub1p", base + "iamo");
924 putIfMissing(namedArgs, "sub2p", base + "iate");
925 putIfMissing(namedArgs, "sub3p", base + "ino");
926 // Imperfect subjunctive
927 putIfMissing(namedArgs, "impsub12s", base + "assi");
928 putIfMissing(namedArgs, "impsub3s", base + "asse");
929 putIfMissing(namedArgs, "impsub1p", base + "assimo");
930 putIfMissing(namedArgs, "impsub2p", base + "aste");
931 putIfMissing(namedArgs, "impsub3p", base + "assero");
933 putIfMissing(namedArgs, "imp2s", base + "a");
934 putIfMissing(namedArgs, "imp3s", base + "i");
935 putIfMissing(namedArgs, "imp1p", base + "iamo");
936 putIfMissing(namedArgs, "imp2p", base + "ate");
937 putIfMissing(namedArgs, "imp3p", base + "ino");
940 itConj(args, namedArgs);
944 private void itConj(List<String> args, Map<String, String> namedArgs) {
945 // TODO Auto-generated method stub
950 private static void putIfMissing(final Map<String, String> namedArgs, final String key,
951 final String value) {
952 final String oldValue = namedArgs.get(key);
953 if (oldValue == null || oldValue.length() == 0) {
954 namedArgs.put(key, value);
958 // TODO: check how ='' and =| are manifested....
959 // TODO: get this right in -are
960 private static void putOrNullify(final Map<String, String> namedArgs, final String key,
961 final String value) {
962 final String oldValue = namedArgs.get(key);
963 if (oldValue == null/* || oldValue.length() == 0*/) {
964 namedArgs.put(key, value);
966 if (oldValue.equals("''")) {
967 namedArgs.put(key, "");
972 static final Pattern whitespace = Pattern.compile("\\s+");
973 static String trim(final String s) {
974 return whitespace.matcher(s).replaceAll(" ").trim();