gpt4 book ai didi

r - 在指定向量的每个元素处分割字符串

转载 作者:行者123 更新时间:2023-12-02 09:33:47 25 4
gpt4 key购买 nike

我正在努力解决一个问题,我确信有一个简单的解决方案,但我一直找不到它。谢谢你的帮助。

每当出现单独向量的元素时,我都会尝试拆分文本字符串。类似于以下内容:

fruits<-c("APPLE","BANANA","ORANGE")
string<-("This is a list of fruits and their properties.
APPLE This is a red fruit, typically very SWEET!
BANANA This is a yellow fruit, also sweet!
ORANGE This is an orange fruit and also, yes, sweet")

我想要的输出是一个由 4 个元素组成的列表/向量,每个元素都包含“fruits”的任何元素出现之前/之后的字符串分割。所以,类似于:

c("This is a list of fruits and their properties",
"APPLE This is a red fruit, typically very SWEET!",
"BANANA This is a yellow fruit, also sweet!,
"ORANGE This is an orange fruit and also, yes, sweet")

我已经尝试过

strsplit(string,split=fruits)

以及其他一些事情,但没有成功。我实际上想做的是将已转换为 .txt 的 .pdf 密码本按与密码本的各个部分相对应的单词(国家/地区)列表进行拆分。

提前致谢!

最佳答案

“我真的不想考虑正则表达式”的方法是执行以下操作:

strsplit(gsub(sprintf('(%s)', paste(fruits, collapse = "|")), 
"MYSPLIT\\1", string),
"MYSPLIT", TRUE)[[1]]
# [1] "This is a list of fruits and their properties. \n "
# [2] "APPLE This is a red fruit, typically very SWEET! \n "
# [3] "BANANA This is a yellow fruit, also sweet! \n "
# [4] "ORANGE This is an orange fruit and also, yes, sweet"

在那里,我基本上匹配了 APPLE、ORANGE 和 BANANA,并将它们替换为 MYSPLITAPPLE 等,为我提供了一个新的分隔符 (MYSPLIT),用于分割字符串。

关于r - 在指定向量的每个元素处分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29719846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com