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_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 )
推荐阅读
- html - 使用指定文本查找属性的值
- ios - 在 Swift 5 中增加 UINavigationBar 的高度
- spring - Best-Precice Check 登录用户 Spring-Boot
- asp.net-mvc - 将记录插入数据库时向 Asp.net MVC 应用程序触发警报
- r - 错误:尝试为 sparklyr ml_lda ml_describe_topics 应用非功能
- docker - 是否可以为多个继承的 Docker 容器启用颜色支持?
- javascript - 在Javascript中的输入字段编号中查找特定数字
- python - Numpy:用前一行的值填充 NaN
- scala - 使用 Scala 和 Play 从 conf 中读取文件!2.5
- python - 使用带有python的rest api将TFS测试用例状态更新为PASS / FAIL