首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从文件中自动提取节(和节标题)

从文件中自动提取节(和节标题)
EN

Stack Overflow用户
提问于 2018-05-09 16:25:15
回答 1查看 293关注 0票数 0

我需要从.Rmd文件中提取所有的子部分(用于进一步的文本分析)和它们的标题(例如,从01-tidy-text.Rmd的整洁文本挖掘书:https://raw.githubusercontent.com/dgrtwo/tidy-text-mining/master/01-tidy-text.Rmd)。

我只知道一个部分从##符号开始,并一直运行到下一个###符号或文件的末尾。

整个文本已经被提取(使用dt <- readtext("01-tidy-text.Rmd"); strEntireText <-dt[1,1])并被定位为变量strEntireText

我想为此使用stringr。或者stringi,类似这样的东西:

代码语言:javascript
运行
复制
 strAllSections <- str_extract(strEntireText , pattern="...")
 strAllSectionsTitles <- str_extract(strEntireText , pattern="...")

请提出你的解决方案。谢谢

本练习的最终目标是能够从data.frame文件中自动创建一个.Rmd文件,其中每一行对应于每个节(和分段),列包含:节标题、节标签、节文本本身和其他一些特定于节的细节,稍后将提取这些信息。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-09 21:46:14

下面是一个使用tidyverse方法的示例。这并不一定适用于您拥有的任何文件--如果您正在使用减价,您可能应该像Spacedman在他的评论中提到的那样,尝试找到一个适当的减价解析库。

代码语言:javascript
运行
复制
library(tidyverse)

## A df where each line is a row in the rmd file.
raw <- data_frame(
  text = read_lines("https://raw.githubusercontent.com/dgrtwo/tidy-text-mining/master/01-tidy-text.Rmd")
)

## We don't want to mark R comments as sections.
detect_codeblocks <- function(text) {
  blocks <- text %>%
    str_detect("```") %>%
    cumsum()

  blocks %% 2 != 0
}

## Here is an example of how you can extract information, such
## headers, using regex patterns.
df <-
  raw %>%
  mutate(
    code_block = detect_codeblocks(text),
    section = text %>%
      str_match("^# .*") %>%
      str_remove("^#+ +"),
    section = ifelse(code_block, NA, section),
    subsection = text %>%
      str_match("^## .*") %>%
      str_remove("^#+ +"),
    subsection = ifelse(code_block, NA, subsection),
    ) %>%
  fill(section, subsection)

## If you wish to glue the text together within sections/subsections,
## then just group by them and flatten the text.
df %>%
  group_by(section, subsection) %>%
  slice(-1) %>%                           # remove the header
  summarize(
    text = text %>%
      str_flatten(" ") %>%
      str_trim()
  ) %>%
  ungroup()

#> # A tibble: 7 x 3
#>   section                          subsection  text                       
#>   <chr>                            <chr>       <chr>                      
#> 1 The tidy text format {#tidytext} Contrastin… "As we stated above, we de…
#> 2 The tidy text format {#tidytext} Summary     In this chapter, we explor…
#> 3 The tidy text format {#tidytext} The `unnes… "Emily Dickinson wrote som…
#> 4 The tidy text format {#tidytext} The gutenb… "Now that we've used the j…
#> 5 The tidy text format {#tidytext} Tidying th… "Let's use the text of Jan…
#> 6 The tidy text format {#tidytext} Word frequ… "A common task in text min…
#> 7 The tidy text format {#tidytext} <NA>        "```{r echo = FALSE} libra…
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50258019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档