首页 > 解决方案 > 结合 spacyr 和 quanteda 生成词形还原语料库或 dfm

问题描述

我了解如何使用 quanteda 构建语料库和 dfm。我也了解如何使用 spacy_parse 对文本或语料库对象进行词形还原。

但我不明白如何在我的语料库中用引理替换原始文本标记。

我希望是这样的:

corpus(my_txt) %>%
  dfm(lemmatize = spacy_parse)

生成引理矩阵,例如:

              be      have      go
first_text    2       6         6
second_text   4       4         2
third_text    6       4         3

相反,我发现的唯一解决方案是从 spacy_parse 输出数据框中的“引理”列重新组合词形化文本,并使用如下代码:

txt_parsed %>% 
select(doc_id, lemma) %>% 
group_by(doc_id) %>% 
summarise(new_txt = str_c(lemma, collapse = " "))

对更好的解决方案有什么建议吗?

标签: rquanteda

解决方案


您可以使用quanteda::as.tokens()将 spacy_parsed 对象转换为令牌。在此之前,您可以将 spacy_parsed 对象的标记列交换为引理列。

txt <- c("I like having to be going.", "Then I will be gone.", "I had him going.")

library("spacyr")

sp <- spacy_parse(txt, lemma = TRUE, entity = FALSE, pos = FALSE)
## Found 'spacy_condaenv'. spacyr will use this environment
## successfully initialized (spaCy Version: 2.3.2, language model: en_core_web_sm)
## (python options: type = "condaenv", value = "spacy_condaenv")
sp$token <- sp$lemma

library("quanteda")
## Package version: 3.0.0
## Unicode version: 10.0
## ICU version: 61.1
## Parallel computing: 12 of 12 threads used.
## See https://quanteda.io for tutorials and examples.
as.tokens(sp) %>%
  dfm()
## Document-feature matrix of: 3 documents, 9 features (37.04% sparse) and 0 docvars.
##        features
## docs    -pron- like have to be go . then will
##   text1      1    1    1  1  1  1 1    0    0
##   text2      1    0    0  0  1  1 1    1    1
##   text3      2    0    1  0  0  1 1    0    0

reprex 包于 2021-04-12 创建 (v2.0.0 )


推荐阅读