【问题标题】:R language/reporteRs loop to write multiple docxR语言/reporteRs循环编写多个docx
【发布时间】:2017-04-14 14:27:53
【问题描述】:

我正在尝试(尽我所能)创建一个脚本,该脚本将使用 R 语言和 reporteRs 从纯文本文件生成格式化的 Word 文档。

要从一个 txt 中提取文本,我使用的是在此线程 Dealing with readLines() function in R 上找到的代码:

fileName <- "C:/MyFolder/TEXT_TO_BE_PROCESSED.txt"
con <- file(fileName,open="r")
line <- readLines(con)
close(con)

然后将提取的文本添加到 docx 中:

doc <- docx(template="temp.docx")

接下来,添加标题(txt 文件的第一行)

doc <- addParagraph( doc, value = line[1], bookmark = "titre", stylename = "Titre")

然后是txt文件的正文

doc <- addParagraph( doc, value = line[2:length(line)], value = line[2:55], stylename = "Contenu")

最后我创建了 docx

writeDoc(doc, file = "output-file.docx")

我希望能够创建一个循环,这样我就可以从多个 txt 文件生成多个 docx。我会非常感谢你的帮助

【问题讨论】:

  • line[2:length(line)] 将提取从第二行到最后的所有内容。您需要使用 lapply 之类的文件名向量来使循环正常工作
  • 感谢您的回复Richard,我在帖子中编辑了与提取txt相关的代码到最后。我不确定如何使用lapply,但我会尝试查看文档。知道的可以帮忙吗?
  • 需要帮助!!!

标签: r docx


【解决方案1】:

你可以用lapply做这样的事情

myFiles <- c("C:/MyFolder/TEXT_TO_BE_PROCESSED.txt", "C:/MyFolder/TEXT_TO_BE_PROCESSED2.txt") # or use list.files()

lapply(myFiles, function(fileName){
  con <- file(fileName,open="r")
  line <- readLines(con) # you could just call readLines(fileName)
  close(con)
  doc <- docx(template="temp.docx")
  doc <- addParagraph( doc, value = line[1], bookmark = "titre", stylename = "Titre")
  doc <- addParagraph( doc, value = line[2:length(line)], value = line[2:55], stylename = "Contenu")
  writeDoc(doc, file = paste0(fileName, "out.docx"))
})

【讨论】:

  • 这是一种魅力!非常感谢您,先生。
  • 我在 writeDoc 行的末尾添加了一个缺失的“)”。我现在应该编辑我的帖子吗?
【解决方案2】:

解决办法:

myFiles <- list.files()

lapply(myFiles, function(fileName){
line <- readLines(fileName)
doc <- docx(template="temp.docx")
doc <- addParagraph( doc, value = line[1], bookmark = "titre", 
stylename = "Titre »)
doc <- addParagraph( doc, value = line[2:length(line)], stylename = "Contenu")
writeDoc(doc, file = paste0(fileName, ".docx"))
})

再次感谢理查德

【讨论】:

    猜你喜欢
    • 2016-09-03
    • 2015-02-13
    • 2016-10-17
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    相关资源
    最近更新 更多