r-结合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 = " "))

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

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

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

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

实际上,我找到了一个更简单的解决方案,那就是在as.tokens函数中使用use_lemm=T选项。示例:

library(spacyr)
spacy_initialize(model = "fr_core_news_sm")
sp1 <- spacy_parse(macron, lemma = TRUE, entity = FALSE, pos = FALSE)
dfm1 <- as.tokens(sp1, use_lemma = T) %>% dfm

相关内容

最新更新