R language/reporteRs循环写入多个docx

R language/reporteRs loop to write multiple docx

我正在尝试(尽我所能)创建一个脚本,该脚本将使用 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文件的body

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

我终于创建了 docx

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

我希望能够创建一个循环,以便从多个 txt 文件生成多个 docx。非常感谢您的帮助

你可以用 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"))
})

解决方案:

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"))
})

再次感谢理查德