How do I count the number of words in a text (string)?

后端 未结 3 1373
死守一世寂寞
死守一世寂寞 2020-12-19 03:36

I have this string vector (for example):

str <- c(\"this is a string current trey\",
    \"feather rtttt\",
    \"tusla\",
    \"laq\")

相关标签:
3条回答
  • 2020-12-19 04:00

    Use the stringi package and 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
    
    0 讨论(0)
  • 2020-12-19 04:01

    You can try

    sapply(gregexpr("\\S+", x), length)
    ## [1] 6 2 1 1
    

    Or as suggested in comments you can try

    sapply(strsplit(x, "\\s+"), length)
    ## [1] 6 2 1 1
    
    0 讨论(0)
  • 2020-12-19 04:06

    Use the wc-function from the qdap package.

    str <- c("this is a string current trey", 
             "feather rtttt", 
             "tusla", 
             "laq")
    
    library("qdap")
    
    wc(str)
    

    That returns:

    wc(str)
    
    [1] 6 2 1 1
    
    0 讨论(0)
提交回复
热议问题