如何以树的形式将树网刮入R列表



我想将(波兰语)维基百科分类的名称以树的形式刮到R列表中,保持树的结构。

我的想法是把所有的类别放到一个列表中,其中的子列表将表示该类别的子类别。问题是,我不知道怎样才能让最穷的孩子们也有同感。

我现在所拥有的,是树的某些级别的单独列表,但它似乎不是最优解决方案。此外,我先抓取链接,然后再抓取类别的名称,做(几乎)完全相同的两次。

这是我目前为止写的代码:

library("stringi")
library("rvest")
find_links <- function(link){
  strona <- read_html(link)
  kategorie <- html_nodes(strona, ".CategoryTreeLabel")
  if(length(kategorie)==0) return(NA)
  as.list(stri_paste("http://pl.wikipedia.org", html_attr(kategorie, "href")))
}
find_titles <- function(link){
  strona <- read_html(link)
  kategorie <- html_nodes(strona, ".CategoryTreeLabel")
  if(length(kategorie)==0) return(NA)
  as.list(html_text(kategorie))
}
link <- 'http://pl.wikipedia.org/wiki/Wikipedia:Drzewo_kategorii'
strona <- read_html(link)
kategorie <- html_nodes(strona, ".CategoryTreeLabel")[-c(1:10, 14, 69, 96, 101, 155, 176, 188, 220, 234)] //don't need these categories
kategorie <- kategorie[220:225] //taking a sample so it doesn't take long
linki <- as.list(stri_paste("http://pl.wikipedia.org", html_attr(kategorie, "href")))
tytuly <- as.list(html_text(kategorie))
tytuly <- list(tytuly, linki)

aa <- rapply(linki, find_links,  how = 'replace')
aa1 <- rapply(linki, find_titles, how = 'replace')
bb <- rapply(aa, find_links,  how = 'replace')
bb1 <- rapply(aa, find_titles,  how = 'replace')
...
下面是bb1(树的第二层)的结果:
> bb1
[[1]]
[[1]][[1]]
[1] NA
[[1]][[2]]
[[1]][[2]][[1]]
[1] "Odznaczenia Związku Ochotniczych Straży Pożarnych Rzeczypospolitej Polskiej"

[[1]][[3]]
[1] NA
[[1]][[4]]
[[1]][[4]][[1]]
[1] "Pożary według państw"

请帮助。我是开放的任何其他解决方案,保持类别的结构。

像这样:

library(stringi)
library(rvest)
library(dplyr)
expand_tree = function(link, level) {
  print(link)
  tree_nodes = 
    link %>%
    read_html %>%
    html_nodes(".CategoryTreeLabel")
  if (length(tree_nodes) > 0)
    data_frame(link = 
                 tree_nodes %>% 
                 html_attr("href") %>%
                 paste0("http://pl.wikipedia.org", .),
               name = html_text(tree_nodes) ) %>%
    setNames(names(.) %>% paste(level, . , sep = ".") ) else data_frame() }
level1 = 
  'http://pl.wikipedia.org/wiki/Wikipedia:Drzewo_kategorii' %>%
  expand_tree("level1") %>%
  slice(-c(1:10, 14, 69, 96, 101, 155, 176, 188, 220, 234)) %>%
  slice(220:225)
level2 = 
  level1 %>%
  group_by(level1.link) %>%
  do(expand_tree(first(.$level1.link), "level2")) %>%
  ungroup
level3 = 
  level2 %>%
  group_by(level2.link) %>%
  do(expand_tree(first(.$level2.link), "level3")) %>%
  ungroup

最新更新