这是一个基于igraph 的解决方案,它使用部分单词标记图形的每个节点,以便使用完整单词命名终端节点:
library(igraph)
library(stringr)
initgraph = function(){
# create a graph with one empty-named node and no edges
g=graph.empty(n=1)
V(g)$name=""
g
}
wordtree <- function(g=initgraph(),wordlist){
for(word in wordlist){
# turns "word" into c("w","wo","wor","word")
subwords = str_sub(word, 1, 1:nchar(word))
# make a graph long enough to hold all those sub-words plus start node
subg = graph.lattice(length(subwords)+1,directed=TRUE)
# set vertex nodes to start node plus sub-words
V(subg)$name=c("",subwords)
# merge *by name* into the existing graph
g = graph.union(g, subg)
}
g
}
加载完毕,
g = wordtree(initgraph(), c("abbey","abbot","abbr","abide"))
plot(g)
得到
您可以将单词作为第一个参数传入现有树中:
> g = wordtree(g,c("now","accept","answer","please"))
> plot(g)
树总是以名称为“”的节点为根,并且所有终端节点(没有出边的节点)都有单词。 igraph 中有一些功能可以在需要时将它们取出。当你完成它时,你实际上并没有说你想用它做什么......或者当我们为你完成它时:)
请注意,有一个很好的绘制树的布局,看起来像您的 ascii 示例:
plot(g,layout=layout.reingold.tilford)