如何计算文本中的单词数(字符串)?

use*_*020 9 regex r apply sapply

我有这个字符串向量(例如):

str <- c("this is a string current trey",
    "feather rtttt",
    "tusla",
    "laq")
Run Code Online (Sandbox Code Playgroud)

为了计算这个向量中的单词数,我使用了这个(这里给出的数字计算R中字符串中的单词数量,这可能是重复但有另一个问题)

No_words <- sapply(gregexpr("\\W+", str), length) + 1
Run Code Online (Sandbox Code Playgroud)

但它回来了

6 2 2 2
Run Code Online (Sandbox Code Playgroud)

String在最后两个位置只有1个元素(即"tusla""laq")

所以应该回来

6 2 1 1
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

Chi*_*til 13

你可以试试

sapply(gregexpr("\\S+", x), length)
## [1] 6 2 1 1
Run Code Online (Sandbox Code Playgroud)

或者根据评论中的建议,您可以尝试

sapply(strsplit(x, "\\s+"), length)
## [1] 6 2 1 1
Run Code Online (Sandbox Code Playgroud)


Spa*_*man 9

使用stringi包裹和stri_count:

require(stringi)
str <- c(
"this is a string current trey",
"nospaces",
"multiple    spaces",
"   leadingspaces",
"trailingspaces    ",
"    leading and trailing    ",
"just one space each")

> stri_count(str,regex="\\S+")
[1] 6 1 2 1 1 3 4
Run Code Online (Sandbox Code Playgroud)