我正在尝试从31个pdf中分别提取一个表。这些表的标题都以相同的方式开头,但结尾因地区而异。
其中一份文件的标题是“表13.1: 2011/12年农业年区、农村和城市居民从事农业的总户数;阿鲁沙地区,2012年人口普查”。另一个是“表13.1: 2011/12农业年度,按地区、农村和城市居民统计的从事农业的家庭总数;多多马地区,2012年人口普查。”
我使用tabulizer根据我需要的特定文本行手动抓取第一个表,但考虑到类似的命名约定,我希望自动执行此过程。
PATH2<- "Regions/02. Arusha Region Profile.pdf“
txt2 <- pdf_text(PATH2) %>%
readr:: read_lines()
```javascript
specific_lines2 2<- txt24621:4639 %>%
str_squish() %>%
str_replace_all(",","") %>%
strsplit(split =“")
发布于 2020-08-28 04:48:00
内容:您可以在每个文件上找到包含标题的公共部分的页面,并从中提取数据(如果每个文件中标题只出现一次)
如何:构建一个函数来获取pdf上的表,然后请求lapply上的函数对所有pdf运行。
示例:
首先,加载该函数以查找包含标题的页面并从中获取文本。
get_page_text <- function(url,word_find) {
txt <- pdftools::pdf_text(url)
p <- grep(word_find, txt, ignore.case = TRUE)[1] # Sentence to find
L <- tabulizer::extract_text(url, pages = p)
i <- which.max(lengths(L))
data.frame(L[[i]])
}
第二,获取文件名。
setwd("C:/Users/xyz/Regions")
files <- list.files(pattern = "pdf$|PDF$") # Get file names on the folder Regions.
然后,使用"loop“(lapply)为每个pdf运行函数。
reports <- lapply(files,
get_page_text,
word_find = "Table 13.1: Total Number of Households Engaged in Agriculture by District, Rural and Urban Residence During 2011/12 Agriculture Year")
结果是一个变量列表,每个提取的pdf都有一个data.frame。接下来就是清理你的数据了。
根据pdf上的模式不同,函数可能会有很大不同。找到页面对我来说很有效,你会找到最适合你的。
https://stackoverflow.com/questions/63283225
复制相似问题