【问题标题】:Count number of verbs for each speech in data frame R计算数据帧 R 中每个语音的动词数
【发布时间】:2017-10-29 18:53:36
【问题描述】:

我有一个如下的数据框:

str(data)
'data.frame':   255 obs. of  3 variables:
$ Group      : Factor w/ 255 levels "AlzGroup1","AlzGroup10",..: 1 112 179 190 201 212 223 234 245 2 ...
$ Gender     : int  1 1 0 0 0 0 0 1 0 0 ...
$ Description: Factor w/ 255 levels "A boy's on the uh falling off the stool picking up cookies . The girl's reaching up for it . The girl the lady "| __truncated__,..: 63 69 38 134 111 242 196 85 84 233 ...

在“描述”列中,我有 255 个演讲,我想在我的数据框中添加一列,其中包含每个演讲中的动词数量,我知道如何获取动词数量,但以下代码给出了描述中的动词总数专栏:

> library(NLP);
> library(tm);
> library(openNLP);
NumOfVerbs=sapply(strsplit(as.character(tagPOS(data$Description)),"[[:punct:]]*/VB.?"),function(x) {res = sub("(^.*\\s)(\\w+$)", "\\2", x); res[!grepl("\\s",res)]} )

有谁知道我如何获得每次演讲中的动词数量?

感谢您的帮助!

埃拉赫

【问题讨论】:

  • 如果你可以计算动词,那么你也可以使用 dplyr::group_by 按语音分组,然后 summarise(n()) 进行计数。我认为如果您发布可重现的示例而不是数据结构,您可能会获得更好的质量帮助。只需使用dput(data) 并将输出粘贴到此处即可。

标签: r nlp text-mining tm opennlp


【解决方案1】:

假设您正在使用与此类似的功能(可在此处找到:could not find function tagPOS):

tagPOS <-  function(x, ...) {
  s <- as.String(x)
  word_token_annotator <- Maxent_Word_Token_Annotator()
  a2 <- Annotation(1L, "sentence", 1L, nchar(s))
  a2 <- annotate(s, word_token_annotator, a2)
  a3 <- annotate(s, Maxent_POS_Tag_Annotator(), a2)
  a3w <- a3[a3$type == "word"]
  POStags <- unlist(lapply(a3w$features, `[[`, "POS"))
  POStagged <- paste(sprintf("%s/%s", s[a3w], POStags), collapse = " ")
  list(POStagged = POStagged, POStags = POStags)
}

创建一个函数,计算包含字母 'VB' 的 POS 标签的数量

count_verbs <-function(x) {
  pos_tags <- tagPOS(x)$POStags
  sum(grepl("VB", pos_tags))
  }

并使用dplyrGroup分组并使用count_verbs()进行汇总:

library(dplyr)
data %>% 
  group_by(Group) %>%
  summarise(num_verbs = count_verbs(Description))

【讨论】:

  • 我无法运行您答案摘要的最后一部分(num_verbs = count_verbs(data$Description)),我收到此错误:summarise_(​​.data, .dots = compat_as_lazy_dots(... )) : 参数“.data”丢失,没有默认值
  • 那是因为你将data$Description作为参数传递给count_verbs(),如果你看上面的链,你会发现我只传递了Description
  • 你是对的,那么使用你在链中所做的会带来一个新的错误!summarise_impl(.data, dots) 中的错误:评估错误:java.lang.OutOfMemoryError: Java heap space, do你知道我们如何使用这个解决方案 NumOfVerbs=sapply(strsplit(as.character(tagPOS(data$Description)),"[[:punct:]]*/VB.?"),function(x) {res = sub("(^.*\\s)(\\w+$)", "\\2", x); res[!grepl("\\s",res)]} ) 计算每个中的动词演讲?
  • 您可以重新启动 R,并使用此 options(java.parameters = "-Xmx8g" )(例如 8 GB,您可以根据您的机器增加/减少它)来增加可以使用的内存。您也可以尝试在tagPOS() 中显式调用垃圾收集器gc() 以释放内存。
  • 非常感谢!这正是我想要的!
猜你喜欢
  • 2017-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
  • 2023-01-14
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多