如何计算文本(字符串)中的单词数? [英] 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")
为了计算这个向量中的单词数,我使用了这个(如这里给出的 计算 R 中字符串中的单词数?,这可能是重复的,但有另一个问题)
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
String 在最后两个位置只有 1 个元素(即 "tusla"
和 "laq"
)
String has only 1 element in last two places (i.e. "tusla"
and "laq"
)
所以它应该返回
6 2 1 1
我该如何解决这个问题?
How do I get around this problem?
推荐答案
你可以试试
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屋!
查看全文