在具有格式化标签(如(的文本中
data.frame(id = c(1, 2), text = c("something here <h1>my text</h1> also <h1>Keep it</h1>", "<h1>title</h1> another here"))
如何使用逗号分隔选项?<h1> </h1>
:中只存在文本
data.frame(text = c("my text, Keep it", "title"), id = c(1, 2))
我们可以使用str_extract_all
。使用regex lookaround,获取标记后的字符,然后在list
输出和paste
上循环提取的字符串
library(stringr)
data.frame(text = sapply(str_extract_all(df1$text, "(?<=<h1>)[^<]+"),
paste, collapse=", "), id = df1$id)
# text id
#1 my text, Keep it 1
#2 title 2
您可以使用网页抓取技能。
library(rvest)
sapply(df$text, function(x) {
read_html(x) %>% html_nodes(css = "h1") %>% html_text %>% toString
}, USE.NAMES = F)
# [1] "my text, Keep it"
# [2] "title"
如果您想使用quanteda,您可以处理将其转换为语料库,然后通过两个corpus_segment()
调用进行处理,一个用于获取之前的文本,另一个用于选择之后的文本。然后,可以使用texts(x, groups = docid())
对文本进行重新分组,指定spacer = ", "
。
以下是如何使用您想要的输出:
library("quanteda")
## Package version: 2.1.1
df <- data.frame(
id = c(1, 2),
text = c("something here <h1>my text</h1> also <h1>Keep it</h1>", "<h1>title</h1> another here")
)
charvec <- corpus(df, docid_field = "id") %>%
corpus_segment("</h1>", pattern_position = "after") %>%
corpus_segment("<h1>", pattern_position = "before") %>%
texts(groups = docid(.), spacer = ", ")
然后将其转换为您想要的data.frame
:
data.frame(text = charvec, id = names(charvec))
## text id
## 1 my text, Keep it 1
## 2 title 2