| 18 | |
| 19 | // constructor takes the name of the two input files |
| 20 | public WordNet(String synsets, String hypernyms) { |
| 21 | if (synsets == null || hypernyms == null) throw new IllegalArgumentException(); |
| 22 | noun2IDs = new TreeMap<>(); |
| 23 | id2Noun = new TreeMap<>(); |
| 24 | In inSyn = new In(synsets); |
| 25 | while (!inSyn.isEmpty()) { |
| 26 | String line = inSyn.readLine(); |
| 27 | String[] fields = line.split(","); |
| 28 | String[] nouns = fields[1].split(" "); |
| 29 | int id = Integer.parseInt(fields[0]); |
| 30 | for (String noun : nouns) { |
| 31 | if (noun2IDs.containsKey(noun)) |
| 32 | noun2IDs.get(noun).add(id); |
| 33 | else { |
| 34 | Bag<Integer> b = new Bag<Integer>(); |
| 35 | b.add(id); |
| 36 | noun2IDs.put(noun, b); |
| 37 | } |
| 38 | } |
| 39 | id2Noun.put(id, fields[1]); |
| 40 | } |
| 41 | Digraph digraph = new Digraph(id2Noun.size()); |
| 42 | In inHyp = new In(hypernyms); |
| 43 | while (!inHyp.isEmpty()) { |
| 44 | String line = inHyp.readLine(); |
| 45 | String[] fields = line.split(","); |
| 46 | int id = Integer.parseInt(fields[0]); |
| 47 | for (int i = 1; i < fields.length; i++) |
| 48 | digraph.addEdge(id, Integer.parseInt(fields[i])); |
| 49 | } |
| 50 | // check multi-roots |
| 51 | int cnt = 0; |
| 52 | for (int i = 0; i < digraph.V(); i++) { |
| 53 | if (digraph.outdegree(i) == 0) |
| 54 | if (++cnt > 1) throw new IllegalArgumentException(); |
| 55 | } |
| 56 | // check cycle |
| 57 | // DirectedCycle cycle = new DirectedCycle(digraph); |
| 58 | // if (cycle.hasCycle()) throw new IllegalArgumentException(); |
| 59 | // check DAG |
| 60 | Topological t = new Topological(digraph); |
| 61 | if (!t.hasOrder()) throw new IllegalArgumentException(); |
| 62 | |
| 63 | sap = new SAP(digraph); |
| 64 | } |
| 65 | |
| 66 | // returns all WordNet nouns |
| 67 | public Iterable<String> nouns() { |