我有一个非常具体的问题。我有一组包含电子邮件(和电子邮件链)的 PDF 文件,通常采用以下格式:
From: Doe, John <[email protected]>
To: Doe, Jane <[email protected]>; Doe, John
Subject: Re: Title
text ...
...
From: Doe, John <[email protected]>
To: Doe, Jane <[email protected]>; Doe, John
CC: Moe, James; Klein, John
Subject: Title
text ...
因此,在一个 PDF 文件中,您通常有多个“from”、“to”和“cc”块。姓名的格式始终是姓氏和名字用逗号分隔。不同的名称用分号分隔。但是,有时完整的电子邮件地址(我不需要)会包含在“<”和“>”之间。我想从这些 PDF 文件中提取所有名称(在 from、to 和 cc 部分),最后输出如下所示:
Last name first name
Doe John
Doe Jane
Moe James
Klein John
我已经设法使用该pdftools
包阅读了 PDF 文件:
files <- list.files(pattern = "pdf$")
pdfs <- lapply(files, pdf_text)
但是,我目前在尝试找到提取所有名称并将它们保存在数据框中的最佳方法时有些困难。我一直在查看str_extract
函数:例如以 开头str_extract(pdfs[[1]], regex("From.*To", ignore_case = TRUE))
,但一直无法找到可行的解决方案。任何帮助将非常感激。例如,假设pdfs[[1]]
包含以下字符串:
teststring <- "From: Doe, John <[email protected]>\r\n
To: Doe, Jane <[email protected]>; Doe, John\r\n
Subject: Re: Title\r\n
text ...\r\n
...\r\n
From: Doe, John <[email protected]>\r\n
To: Doe, Jane <[email protected]>; Doe, John\r\n
CC: Moe, James; Klein, John\r\n
Subject: Title\r\n
text ...\r\n"
试试这个,使用 teststring
library(stringr)
fullnames <- unique(c(str_extract_all(teststring, "[a-zA-Z]+,\\s[a-zA-Z]+", simplify=TRUE)))
splitnames <- unlist(strsplit(fullnames, ","))
ans <- data.frame(Last=splitnames[c(TRUE,FALSE)], First=splitnames[c(FALSE,TRUE)])
输出
Last First
1 Doe John
2 Doe Jane
3 Moe James
4 Klein John
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句