正则表达式 – 如何计算文本中的单词数(字符串)?
发布时间:2020-12-14 06:30:44 所属栏目:百科 来源:网络整理
导读:我有这个字符串向量(例如): str - c("this is a string current trey","feather rtttt","tusla","laq") 为了计算这个向量中的单词数,我使用了这个(这里给出的是Count the number of words in a string in R?,这可能是重复但有另一个问题) No_words - sapply
我有这个字符串向量(例如):
str <- c("this is a string current trey","feather rtttt","tusla","laq") 为了计算这个向量中的单词数,我使用了这个(这里给出的是Count the number of words in a string in R?,这可能是重复但有另一个问题) No_words <- sapply(gregexpr("W+",str),length) + 1 但它回来了 6 2 2 2 String在最后两个位置只有1个元素(即“tusla”和“laq”) 所以应该回来 6 2 1 1 我该如何解决这个问题?
你可以试试
sapply(gregexpr("S+",x),length) ## [1] 6 2 1 1 或者根据评论中的建议,您可以尝试 sapply(strsplit(x,"s+"),length) ## [1] 6 2 1 1 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |