使用 R 提取 POS 标签

Extracting the POS tags in R using

在我的数据集中,我试图为每个观察分别创建包含名词、动词和形容词数量的变量。使用 openNLP 包我已经成功做到了这一点:

s <- paste(c("Pierre Vinken, 61 years old, will join the board as a ",
             "nonexecutive director Nov. 29.\n",
             "Mr. Vinken is chairman of Elsevier N.V., ",
             "the Dutch publishing group."),
           collapse = "")
s <- as.String(s)
s

sent_token_annotator <- Maxent_Sent_Token_Annotator()
word_token_annotator <- Maxent_Word_Token_Annotator()
a2 <- annotate(s, list(sent_token_annotator, word_token_annotator))
pos_tag_annotator <- Maxent_POS_Tag_Annotator()
pos_tag_annotator
a3 <- annotate(s, pos_tag_annotator, a2)
a3
a3w <- subset(a3, type == "word")
a3w

这给了我输出:

id type     start end features
1 sentence     1  84 constituents=<<integer,18>>
2 sentence    86 153 constituents=<<integer,13>>
3 word         1   6 POS=NNP
4 word         8  13 POS=NNP
5 word        14  14 POS=,

以此类推

我的问题是,如何提取每次观察的名词数量,以便我可以将其用于进一步分析。

谢谢!

我不使用 openNLP,但使用不同的软件包进行 POS 标记。如果有人对 openNLP 的答案有帮助,那就太好了。

但是我会用udpipe给你一个解决方案。您可能会发现它很有用。

s <- paste(c("Pierre Vinken, 61 years old, will join the board as a ",
             "nonexecutive director Nov. 29.\n",
             "Mr. Vinken is chairman of Elsevier N.V., ",
             "the Dutch publishing group."),
           collapse = "")

library(udpipe)

if (file.exists("english-ud-2.0-170801.udpipe")) 
  ud_model <- udpipe_load_model(file = "english-ud-2.0-170801.udpipe") else {
    ud_model <- udpipe_download_model(language = "english")
    ud_model <- udpipe_load_model(ud_model$file_model)
}

x <- udpipe_annotate(ud_model, s)
x <- as.data.frame(x)
table(x$upos)

  ADJ   ADP   AUX   DET  NOUN   NUM PROPN PUNCT  VERB 
    2     2     2     3     6     2     8     5     1 

编辑:每句计数:

table(x$sentence_id, x$upos)
    ADJ ADP AUX DET NOUN NUM PROPN PUNCT VERB
  1   2   1   1   2    3   2     3     3    1
  2   0   1   1   1    3   0     5     2    0

当你在注释之后从 x 创建一个 data.frame 时,你可以访问 doc_id、paragraph_id、sentence_id 等。你可以创建一个整体每个文档/句子等的统计范围。小插图很好地概述了可能的情况。