gpt4 book ai didi

regex - 在 R Dataframe 列中拆分单词

转载 作者:行者123 更新时间:2023-12-02 04:40:59 26 4
gpt4 key购买 nike

我有一个数据框,其中一列中的单词由单个空格分隔。我想将其分为以下三种类型。数据框如下所示。

Text
one of the
i want to

我想把它分成如下。

Text         split1     split2    split3
one of the one one of of the

我能够取得第一名。无法弄清楚其他两个。

我得到 split1 的代码:

new_data$split1<-sub(" .*","",new_data$Text)

找出 split2:

df$split2 <- gsub(" [^ ]*$", "", df$Text)

最佳答案

我们可以尝试使用 gsub。捕获一个或多个非空白 (\\S+) 作为一组(在本例中有 3 个单词),然后在替换中,我们重新排列反向引用并插入一个分隔符 ( ,),我们使用它来通过 read.table 转换为不同的列。

 df1[paste0("split", 1:3)] <- read.table(text=gsub("(\\S+)\\s+(\\S+)\\s+(\\S+)", 
"\\1,\\1 \\2,\\2 \\3", df1$Text), sep=",")
df1
# Text split1 split2 split3
#1 one of the one one of of the
#2 i want to i i want want to

数据

df1 <- structure(list(Text = c("one of the", "i want to")), 
.Names = "Text", class = "data.frame", row.names = c(NA, -2L))

关于regex - 在 R Dataframe 列中拆分单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37615636/

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