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

问题描述 投票:0回答:1

以下代码在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

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

我也想替代“香蕉”,“水果”“南瓜”,“蔬菜”

我可以列出大型文件吗?

谢谢

r text gsub
1个回答
0
投票

如果是子字符串替换,则选项为带有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"  
© www.soinside.com 2019 - 2024. All rights reserved.