2014-05-22 20 views
7

devo questo vettore stringa (per esempio):Come faccio a contare il numero di parole in un testo (stringa)?

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

per contare il numero di parole in questo vettore ho usato questo (come qui proposta Count the number of words in a string in R?, che è un possibile duplicato ma con un altro problema)

No_words <- sapply(gregexpr("\\W+", str), length) + 1 

ma restituisce

6 2 2 2 

String ha solo 1 elemento in ultimi due posti (cioè "tusla" e "laq")

quindi dovrebbe tornare

6 2 1 1 

Come faccio a risolvere questo problema?

+4

'sapply (strsplit (str," "), lunghezza)' funziona per me. –

+0

Prova "sum (No_words)" –

+0

@ RomanLuštrik cosa succede se la stringa ha più spazi tra poche parole? per esempio. str <- c ("questa è una stringa Trey corrente", "piuma rtttt", "Tusla", "laq") Poi non funziona. Conta anche quegli spazi extra. Spero che capisca cosa sto cercando di dire. – user3664020

risposta

12

Si può provare

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

O come suggerito nei commenti si può provare

sapply(strsplit(x, "\\s+"), length) 
## [1] 6 2 1 1 
+0

La tua seconda risposta non riesce su "iniziale e finale", restituendo 4. – Spacedman

+0

la prima risposta non riesce con le stringhe vuote "" restituisce 1 – jpmarindiaz

7

Utilizzare il stringi pacchetto e 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

buono come il metodo sapply – Facottons