【发布时间】:2017-09-27 19:25:28
【问题描述】:
目前我有一个代码可用于一个单词搜索,我们可以搜索多个单词并将这些匹配的单词写入数据框中吗? (为了澄清,请参阅此post)这是akrun's 解决方案,适用于一个词。 代码如下:
library(pdftools)
library(tesseract)
All_files <- Sys.glob("*.pdf")
v1 <- numeric(length(All_files))
word <- "school"
df <- data.frame()
Status <- "Present"
for (i in seq_along(All_files)){
file_name <- All_files[i]
cnt <- pdf_info(All_files[i])$pages
print(cnt)
for(j in seq_len(cnt)){
img_file <- pdftools::pdf_convert(All_files[i], format = 'tiff', pages = j, dpi = 400)
text <- ocr(img_file)
ocr_text <- capture.output(cat(text))
check <- sapply(ocr_text, paste, collapse="")
junk <- dir(path= paste0(path, "/tiff"), pattern="tiff")
file.remove(junk)
br <-if(length(which(stri_detect_fixed(tolower(check),tolower(word)))) <= 0) "Not Present"
else "Present"
print(br)
if(br=="Present") {
v1[i] <- j
break}
}
Status <- if(v1[i] == 0) "Not Present" else "Present"
pages <- if(v1[i] == 0) "-" else
paste0(tools::file_path_sans_ext(basename(file_name)), "_", v1[i])
words <- if(v1[i] == 0) "-" else word
df <- rbind(df, cbind(file_name = basename(file_name),
Status, pages = pages, words = words))
}
这里我们只搜索一个词,即school。我们可以搜索多个单词,如school、gym、swimming pool?
预期 O/P
fileName Status Page Words TEXT
test.pdf Present test_1 gym I go gym regularly
test.pdf Present test_3 school Here is the next school
test1.pdf Present test1_4 swimming pool In swimming pool
test1.pdf Present test1_7 gym next to Gold gym
test2.pdf Not Present - -
文件名=文件名
状态=如果找到任何单词,则“存在”,否则“不存在”
Page=这里“_1”、“_3”定义了找到单词的页码;;在“test_1”页找到了“gym”一词,在“test_3”页找到了“school”。
单词=找到所有单词;;就像在 test.pdf 文件的第 1 页和第 3 页上只找到“健身房”和“学校”,在 test1.pdf 文件的第 4 页和第 7 页上只找到“游泳池”和“健身房”。
TEXT = 找到该词的文本
对此的任何建议都会有所帮助。
谢谢
【问题讨论】:
-
检查 grepl() 并使用类似“(word|gym|swimming pool)”的东西作为模式。它将返回 TRUE 或 FALSE,具体取决于您的单词是否存在。我可以稍后在我的电脑上查看它
-
ifelse(grepl("Swimming|Hanging", check), "Present", "Not Present").. 这将返回存在或不存在,但仍无法在数据框中附加那些匹配的单词。
-
要提取匹配的单词,请查看
stringr的str_extract_all。您必须进行一些进一步的清理才能将唯一的单词粘贴在一起并将它们附加到您的 data.frame