R语言 将句子还原为单词

zte4gxcn  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(113)

我正在寻找一种有效的方法来减少一个大句子到一个特定的长度和结束一个完整的词。
例如,将每个句子减少到最多24个字符,并以整个单词结束。

fruits <- c(
  "apples and oranges and pears and bananas",
  "pineapples and mangos and guavas"
)

字符串

"apples and oranges and", "pineapples and mangos"

zbdgwd5y

zbdgwd5y1#

取一个额外的字符,然后删除最后一个空格之后(包括)的所有内容。

fruits <- c(
  "apples and oranges and pears and bananas",
  "pineapples and mangos and guavas"
)

n <- 24

sub(
  " [^ ]*$",
  "",
  substr(fruits, 1, n + 1)
)
#> [1] "apples and oranges and" "pineapples and mangos"

字符串

m4pnthwp

m4pnthwp2#

sub的另一个选项

> sub("(.{1,24}(?<=\\S)(?= )).*", "\\1", fruits, perl = TRUE)
[1] "apples and oranges and" "pineapples and mangos"

字符串

相关问题