[英]Ignore errors in readtext r
我现在正在尝试使用 readtext 提取放置在一个文件夹中的大量 docx 文件(1500 个)(在使用 list.files 创建列表之后)
您可以在此处找到类似的示例: https://cran.r-project.org/web/packages/readtext/vignettes/readtext_vignette.html
我收到一些文件错误(下面的示例),问题是发生此错误时,提取过程停止。 我可以通过更改verbosity = 3
来识别有问题的文件,但随后我必须重新启动提取过程(以查找另一个有问题的文件)。
我的问题是,如果遇到错误,是否有办法避免中断进程?
我更改ignore_missing_files = TRUE
但这并没有解决问题。
遇到的错误示例:
write error in extracting from zip file
Error: 'C:\Users--- c/word/document.xml' does not exist.
很抱歉没有发布可重现的示例,但我不知道如何发布带有大型 docx 文件的示例。 但这是代码:
library(readtext)
data_files <- list.files(path = "PATH", full.names = T, recursive = T) # PATH = the path to the folder where the documents are located
extracted_texts <- readtext(data_files, docvarsfrom = "filepaths", dvsep = "/", verbosity = 3, ignore_missing_files = TRUE) # this is to extract the text in the files
write.csv2(extracted_texts, file = "data/text_extracts.csv", fileEncoding = "UTF-8") # this is to export the files into csv
让我们首先整理一个可重现的示例:
download.file("https://file-examples-com.github.io/uploads/2017/02/file-sample_1MB.docx", "test1.docx")
writeLines("", "test2.docx")
我在这里生成的第一个文件应该是一个正确的 docx 文件,第二个是垃圾文件。
我会将readtext
包装在一个处理错误和警告的小 function 中:
readtext_safe <- function(f) {
out <- tryCatch(readtext::readtext(f),
error = function(e) "fail",
warning = function(e) "fail")
if (isTRUE("fail" == out)) {
write(f, "errored_files.txt", append = TRUE)
} else {
return(out)
}
}
请注意,我将错误和警告视为相同,这可能不是您真正想要的。 我们可以使用这个 function 来遍历您的文件:
files <- list.files(pattern = ".docx$", ignore.case = TRUE, full.names = TRUE)
x <- lapply(files, readtext_safe)
x
#> [[1]]
#> readtext object consisting of 1 document and 0 docvars.
#> # Description: df[,2] [1 × 2]
#> doc_id text
#> <chr> <chr>
#> 1 test1.docx "\"Lorem ipsu\"..."
#>
#> [[2]]
#> NULL
在结果列表中,失败的文件只有一个NULL
条目,因为没有返回任何内容。 我喜欢写出这些错误文件的列表,上面的 function 创建了一个 txt 文件,如下所示:
readLines("errored_files.txt")
#> [1] "./test2.docx"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.