【发布时间】:2019-05-24 23:11:48
【问题描述】:
我想像这样获取一个 xml 文件(我称之为“2019-05-24.xml”):
<file>
<header>
<filename>2019-05-24</filename>
</header>
<body>
<div type="article">
<head>First test article</head>
<p>Some information.</p>
<p>Some other information.</p>
</div>
<div type="section" feature="essay">
<head>Test essay</head>
<p>An argument.</p>
<p>Supporting evidence.</p>
</div>
</body>
</file>
然后把它变成这样的小标题
# A tibble: 3 x 6
filename seq type feature head text
<chr> <int> <chr> <chr> <chr> <chr>
1 2019-05-24.xml 1 article NA First test "Some information. Other information. Yet…
2 2019-05-24.xml 2 section essay Test essay "An argument. Supporting evidence."
3 2019-05-24.xml 3 index NA NA "Article.....1 Essay....2"
这让我走到了一半:
sample <- "2019-05-24.xml"
extract_data <- function(x){
divs <- x %>%
read_xml() %>%
xml_child(2) %>%
xml_find_all(".//div")
text <- xml_text(divs)
type <- xml_attr(divs, "type")
feature <- xml_attr(divs, "feature")
seq <- seq_along(divs)
test_tibble <- tibble(filename = x, seq = seq, type = type, feature = feature, text = text)
}
lapply(sample, extract_data)
不幸的是,结果连接了head 和p 文本:
# A tibble: 3 x 5
filename seq type feature text
<chr> <int> <chr> <chr> <chr>
1 2019-05-24.… 1 article NA "First test articleSome information.\n Other in…
2 2019-05-24.… 2 section essay Test essayAn argument.Supporting evidence.
3 2019-05-24.… 3 index NA Article.....1Essay....2
问题1:头部
如果我以与提取文本相同的方式提取head
head <- sample %>%
read_xml() %>%
xml_child(2) %>%
xml_find_all(".//div/head//text()")
我收到一个错误,因为第三个div 不包含head:
Error: Tibble columns must have consistent lengths, only values of length one are recycled:
* Length 2: Column `head`
* Length 3: Columns `seq`, `type`, `feature`
如果div 中没有head,我能否让这个函数返回NA?
问题 2:在 div 中读取文本
我只想阅读divs 列表中三个项目或节点中的每一个中的文本。我可以让text <- divs %>% xml_children %>% xml_text()(它返回整个文件中的每个孩子)在每个节点上单独工作吗?我尝试了各种apply() 变体。我想我在 XPath 和 xml_find_all 和 xml_text 上做错了,但我想不通。
【问题讨论】: