首页 > 解决方案 > 是否有用于在特定“单词距离”内查找关键字的 R 函数?

问题描述

我需要的是在某个“单词距离”内查找单词的功能。“包”和“工具”这两个词在“他的车里有一袋工具”这句话很有趣。

使用 Quanteda kwic 功能,我可以分别找到“包”和“工具”,但这通常会给我带来过多的结果。我需要例如“包”和“工具”在五个字以内。

标签: rquanteda

解决方案


您可以使用该fcm()函数计算固定窗口内的共现,例如 5 个单词。这会创建一个“特征共现矩阵”,并且可以为任何大小的令牌跨度或整个文档的上下文定义。

对于您的示例,或者至少是基于我对您的问题的解释的示例,如下所示:

library("quanteda")
## Package version: 1.4.3
## Parallel computing: 2 of 12 threads used.
## See https://quanteda.io for tutorials and examples.

txt <- c(
  d1 = "He had a bag of tools in his car",
  d2 = "bag other other other other tools other"
)
fcm(txt, context = "window", window = 5)
## Feature co-occurrence matrix of: 10 by 10 features.
## 10 x 10 sparse Matrix of class "fcm"
##         features
## features He had a bag of tools in his car other
##    He     0   1 1   1  1     1  0   0   0     0
##    had    0   0 1   1  1     1  1   0   0     0
##    a      0   0 0   1  1     1  1   1   0     0
##    bag    0   0 0   0  1     2  1   1   1     4
##    of     0   0 0   0  0     1  1   1   1     0
##    tools  0   0 0   0  0     0  1   1   1     5
##    in     0   0 0   0  0     0  0   1   1     0
##    his    0   0 0   0  0     0  0   0   1     0
##    car    0   0 0   0  0     0  0   0   0     0
##    other  0   0 0   0  0     0  0   0   0    10

在这里,术语bag在第一个文档中的tool的 5 个标记内出现一次。在第二个文档中,它们相距超过 5 个令牌,因此不计算在内。


推荐阅读