/** * Turns a sentence into a flat phrasal tree. The structure is S -> tag*. And then each tag goes * to a word. The tag is either found from the label or made "WD". The tag and phrasal node have a * StringLabel. * * @param s The Sentence to make the Tree from * @param lf The LabelFactory with which to create the new Tree labels * @return The one phrasal level Tree */ public static Tree toFlatTree(Sentence<?> s, LabelFactory lf) { List<Tree> daughters = new ArrayList<Tree>(s.length()); for (HasWord word : s) { Tree wordNode = new LabeledScoredTreeLeaf(lf.newLabel(word.word())); if (word instanceof TaggedWord) { TaggedWord taggedWord = (TaggedWord) word; wordNode = new LabeledScoredTreeNode( new StringLabel(taggedWord.tag()), Collections.singletonList(wordNode)); } else { wordNode = new LabeledScoredTreeNode(lf.newLabel("WD"), Collections.singletonList(wordNode)); } daughters.add(wordNode); } return new LabeledScoredTreeNode(new StringLabel("S"), daughters); }
/** * Recursively transforms each node of <code>tree</code> parameter according to the passed in * <code>LabelFactory</code>. None of the structure of the <code>Tree</code> is altered only the * information stored in the Label at each node. * * @param <S> Original Tree label type * @param <T> Output tree label type * @param tree * @param labelFactory * @return Tree with transformed labels according to <code>labelFactory</code> */ public static <S, T> Tree<T> transformTreeLabels(Tree<S> tree, LabelFactory<S, T> labelFactory) { T newLabel = labelFactory.newLabel(tree); List<Tree<T>> newChildren = new ArrayList<Tree<T>>(); for (Tree<S> node : tree.getChildren()) { Tree<T> newNode = transformTreeLabels(node, labelFactory); newChildren.add(newNode); } return new Tree<T>(newLabel, newChildren); }