3

我有一个文本,例如

text<- "i am happy today :):)"

我想从文本向量中提取 :) 并报告它的频率

4

3 回答 3

5

这是一个很容易概括的想法:

text<- c("i was happy yesterday :):)",
         "i am happy today :)",
         "will i be happy tomorrow?")

(nchar(text) - nchar(gsub(":)", "", text))) / 2
# [1] 2 1 0
于 2012-04-11T07:44:45.737 回答
3

我假设您只想要计数,还是您也想:)从字符串中删除?

对于计数,您可以执行以下操作:

length(gregexpr(":)",text)[[1]])

这给出了 2。字符串向量的更通用的解决方案是:

sapply(gregexpr(":)",text),length)

编辑:

Josh O'Brien 指出,这也返回 1 of there is no since return:)在这种情况下。要解决此问题,您可以使用:gregexpr-1

sapply(gregexpr(":)",text),function(x)sum(x>0))

这确实变得不那么漂亮了。

于 2012-04-11T07:50:58.317 回答
1

这可以解决问题,但可能不是最直接的方法:

mytext<- "i am happy today :):)"

# The following line inserts semicolons to split on
myTextSub<-gsub(":)", ";:);", mytext)

# Then split and unlist
myTextSplit <- unlist(strsplit(myTextSub, ";"))

# Then see how many times the smiley turns up
length(grep(":)", myTextSplit))

编辑

要处理长度 > 1 的文本向量,请不要取消列出:

mytext<- rep("i am happy today :):)",2)
myTextSub<-gsub(":\\)", ";:\\);", mytext)
myTextSplit <- strsplit(myTextSub, ";")

sapply(myTextSplit,function(x){
  length(grep(":)", x))
})

但我更喜欢其他答案。

于 2012-04-11T07:43:03.163 回答