如何计算文本(字符串)中的单词数? [英] How do I count the number of words in a text (string)?
本文介绍了如何计算文本(字符串)中的单词数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个字符串向量(例如):
I have this string vector (for example):
str <- c("this is a string current trey",
"feather rtttt",
"tusla",
"laq")
To count the number of words in this vector I used this (as given here Count the number of words in a string in R?, which is a possible duplicate but with another issue)
No_words <- sapply(gregexpr("\\W+", str), length) + 1
但返回
6 2 2 2
字符串的最后两个位置只有1个元素(即"tusla"
和"laq"
)
String has only 1 element in last two places (i.e. "tusla"
and "laq"
)
因此它应该返回
6 2 1 1
如何解决这个问题?
推荐答案
您可以尝试
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
这篇关于如何计算文本(字符串)中的单词数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文