gpt4 book ai didi

regex - 字符串在数字单词模式上分割

转载 作者:行者123 更新时间:2023-12-04 13:37:50 24 4
gpt4 key购买 nike

我有一个看起来像这样的数据框:

V1                        V2
peanut butter sandwich 2 slices of bread 1 tablespoon peanut butter

我的目标是:
V1                        V2
peanut butter sandwich 2 slices of bread
peanut butter sandwich 1 tablespoon peanut butter

我曾尝试使用 strsplit(df$v2, " ")分割字符串,但只能用 " "分割。我不确定是否只能在第一个数字处分割字符串,然后将字符取至下一个数字。

最佳答案

您可以按以下方式拆分字符串:

txt <- "2 slices of bread 1 tablespoon peanut butter"

strsplit(txt, " (?=\\d)", perl=TRUE)[[1]]
#[1] "2 slices of bread" "1 tablespoon peanut butter"

这里使用的正则表达式正在寻找空格,后跟数字。它使用零宽度正向超前 (?=)表示,如果空格后跟数字( \\d),则这是我们要分割的空格类型。为什么零宽度向前看?这是因为我们不想将数字用作拆分字符,我们只想匹配数字后面的任何空格。

要使用该想法并构建您的数据框架,请参见以下示例:
item <- c("peanut butter sandwich", "onion carrot mix", "hash browns")
txt <- c("2 slices of bread 1 tablespoon peanut butter", "1 onion 3 carrots", "potato")
df <- data.frame(item, txt, stringsAsFactors=FALSE)

# thanks to Ananda for recommending setNames
split.strings <- setNames(strsplit(df$txt, " (?=\\d)", perl=TRUE), df$item)
# alternately:
#split.strings <- strsplit(df$txt, " (?=\\d)", perl=TRUE)
#names(split.strings) <- df$item

stack(split.strings)
# values ind
#1 2 slices of bread peanut butter sandwich
#2 1 tablespoon peanut butter peanut butter sandwich
#3 1 onion onion carrot mix
#4 3 carrots onion carrot mix
#5 potato hash browns

关于regex - 字符串在数字单词模式上分割,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387994/

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