从文本文档中提取粗体和斜体文本

extract bold and italic text from a text document

我有文本文件,我用粗体和斜体突出显示某些文本。我想要一个读取 .txt 文件并将所有粗体或斜体文本导出到另一个文档(文本文件)的脚本。

有人知道办法吗?

最好是R方案,但可以尝试其他方案。

Mac 用户

假设我们有一个 Markdown 格式的文本文件 ìn.md 并且我们想要创建另一个仅包含斜体和粗体部分的 Markdown 文件 out.md

文件内容 in.md:

# Header

There is *italic* and **bold** text!
There is *another italic* and **another bold** text!
library(tidyverse)

text <- read_file("in.md")
bold_texts <- text %>%
  str_extract_all("\*\*[^\*]+\*\*") %>%
  purrr::simplify() %>%
  map_chr(~ .x %>% str_remove_all("\*"))
bold_texts
#> [1] "bold"         "another bold"
italic_texts <-
  text %>%
  str_remove_all(bold_texts %>% map_chr(~ paste0("\*\*", .x, "\*\*")) %>% paste0(collapse = "|")) %>%
  str_extract_all("\*[^\*]+\*") %>%
  purrr::simplify() %>%
  map_chr(~ .x %>% str_remove_all("\*"))
italic_texts
#> [1] "italic"         "another italic"

out_text <- c("#Bold texts:", bold_texts, "#Italic texts:", italic_texts) %>% paste0(collapse = "\n")
cat(out_text)
#> #Bold texts:
#> bold
#> another bold
#> #Italic texts:
#> italic
#> another italic
write_file(out_text, "out.md")

reprex package (v2.0.1)

于 2021-11-23 创建