【问题标题】:How to read XML files containing multiple "documents" into R for text analysis?如何将包含多个“文档”的 XML 文件读入 R 进行文本分析?
【发布时间】:2019-10-09 16:10:47
【问题描述】:

我正在尝试使用 R 中的 Quanteda 包将多个 XML 文件转换为文档语料库以进行文本分析。如何以允许将它们制作成语料库的方式在 R 中加载文件?

每个 XML 文件都包含来自 16 篇文章(标题、链接)的元数据和文本。我有 119 个这样的 XML 文件。

这是我正在使用的 xml 文件的示例:

<item><title>Aseguran que este sábado se verá en las góndolas la rebaja del IVA en alimentos</title>
<link>https://www.losandes.com.ar/article/view?slug=aseguran-que-este-sabado-se-vera-en-las-gondolas-la-rebaja-del-iva-en-alimentos</link><guid>https://www.losandes.com.ar/article/view?slug=aseguran-que-este-sabado-se-vera-en-las-gondolas-la-rebaja-del-iva-en-alimentos</guid><description>Según el presidente de la Asociación de Supermercados Unidos, algunas cadenas podrían aplicar los cambios dispuestos por el Gobierno.</description></item>

<item><title>Vélez: Fernando Gago concentra para el duelo contra Lanús</title><link>https://www.losandes.com.ar/article/view?slug=velez-fernando-gago-concentra-para-el-duelo-contra-lanus</link><guid>https://www.losandes.com.ar/article/view?slug=velez-fernando-gago-concentra-para-el-duelo-contra-lanus</guid><description>El ex mediocampista de Boca se entrenó en Liniers y podría ser parte del equipo que el domingo visitará a Lanús, a las 17.45.</description></item>

<item><title>Scaloni prepara la lista para la gira del seleccionado argentino por los Estados Unidos</title><link>https://www.losandes.com.ar/article/view?slug=scaloni-prepara-la-lista-para-la-gira-del-seleccionado-argentino-por-los-estados-unidos</link><guid>https://www.losandes.com.ar/article/view?slug=scaloni-prepara-la-lista-para-la-gira-del-seleccionado-argentino-por-los-estados-unidos</guid><description>Argentina tiene programado dos amistosos en EEUU frente a Chile y México a principio de septiembre y el domingo confirmaría la nómina. </description></item>

我无法弄清楚如何将这些文本读入 R,而 Quanteda 可以识别每个文件包含 16 个单独的文档。

我已经设法创建了一个列表,其中包含每个 xml 文件的子列表。这似乎并没有真正起作用或让我到达我想要的地方。

我也尝试过简单地使用 Quanteda 附带的 readtext 函数,因为它应该能够读取 xml,但我得到一个错误(如下所示)。

rm(list=ls())
setwd("~/research projects/data expansion")
library(rvest)
library(stringr)
library(dplyr)


# Here is what I tried to do first:

setwd("data expansion/")
filename <- list.files()


# the first three functions on this page save the title, description, and link for each article
# as character vectors

get.desc <- function(x){
    page <- read_html(x)
    desc <- html_nodes(page, "item")
    desc <- html_nodes(desc, "description")
    text <- html_text(desc)
}

get.title <- function(x){
  page <- read_html(x)
  title <- html_nodes(page, "item")
  title <- html_nodes(title, "title")
  text <- html_text(title)
}

get.link <- function(x){
  page <- read_html(x)
  link <- html_nodes(page, "item")
  link <- html_nodes(link, "guid")
  text <- html_text(link)
}

# to.collect is a function that iterates that last three "get" functions
# and then stores that information into a list

to.collect<-function(file=file){
    N <- length(file)

    my.store <- vector("list", N)

    for(i in 1:N){

      my.store[[i]][[1]] <- get.title(file[i])
      my.store[[i]][[2]] <- get.desc(file[i])
      my.store[[i]][[3]] <- get.link(file[i])

                }  
    my.store
}


# This loop iterates the to.collect function over every file in the folder
# and then stores each file's information into a larger list called "files_all"
N <- length(all_files)
files_all <- list()
for (i in 1:N) {
  test <- to.collect(file = all_files[i])

  title <- test[[1]][1]
  desc <- test[[1]][2]
  link <- test[[1]][3]

  name <- paste(filename[i],sep = "")
  tmp <- list(title=title,description=desc,link=link)
  files_all[[name]] <- tmp
}

我不知道从这里做什么......所以我现在放弃了

这是我尝试简单地使用 readtext()

#install.packages("quanteda")
#install.packages("readtext")
library(XML)
library(xml2)
library(readtext)
library(quanteda)

texts <- readtext("*.xml")

我希望,当使用 readtext 时,结果应该是一个临时文件,其中包含现在已解析的 xml 文件,我可以将其转换为语料库。相反,我得到了这个错误:

> texts <- readtext("*.xml")

Error in xml2_to_dataframe(xml) : 
  The xml format does not fit for the extraction without xPath
  Use xPath method instead

【问题讨论】:

    标签: r xml quanteda


    【解决方案1】:

    你想要完成的事情可以这样完成。我准备了两个函数

    1. 解析每个“item”节点的函数
    2. 处理整个文件的功能
    library(tidyverse)
    library(rvest)
    
    ## function to parse each item_node
    parse_item <- function(nod){
     return(data.frame(title = nod %>% html_nodes('title') %>% html_text,
                       description = nod %>% html_nodes('description') %>% html_text,
                       link = nod %>% html_nodes('guid') %>% html_text,
                       stringsAsFactors = F))
    }
    
    ## function to process entire file
    parse_file <- function(filename){
      read_html(filename) %>% # read file
        html_nodes("item") %>% # extract item nodes
        lapply(parse_item) %>% # apply parse_item() function to each nodes
        bind_rows() # stach up the each item into one data.frame
    }
    

    以下两行将创建一个新的data.frame。

    files <- list.files(pattern = ".xml")
    entire_dataset <- lapply(files, parse_file) %>% bind_rows()
    

    【讨论】:

      猜你喜欢
      • 2017-07-20
      • 1970-01-01
      • 2014-11-22
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多