使用具有多个条件的 gsub 替换 PDF 中的单词列表

Using gsub with multiple conditions to substitute a list of words in a PDF

以下代码在 r 中有效:

pdf <- pdf_text("xyz.pdf") 
text <- c(pdf)
text_df <- tibble(line = 1:2, text = text)
words <- text_df %>%
unnest_tokens(word, text) 
x <- words
y <- gsub("apple","fruit", x) 
y

我需要帮助的是为子项添加多个条件:

我也想换 "banana"、"fruit" "squash"、"vegetable"

我可以为大型文档制作列表吗?

谢谢

如果是子串替换,一个选项就是一个带gsub的循环。为模式和替换创建两个向量(具有相同的长度),然后遍历向量的序列并用 gsub 进行替换并将其分配给同一对象

pat <- c("apple", "banana", "squash")
replace <- c("fruit", "fruit", "vegetable")
for(i in seq_along(pat)) x<- gsub(pat[i], replace[i], x)

如果是固定匹配,我们不需要gsub,因为我们可以使用命名向量进行匹配并替换

x <- c("apple", "apple", "banana", "squash", "banana")
unname(setNames(replace, pat)[x])
#[1] "fruit"     "fruit"     "fruit"     "vegetable" "fruit"