Quanteda:当短语之间有任意数量的单词时,如何查找短语中两个或多个单词的模式?

问题描述 投票:0回答:1

我想使用包{quanteda}tokens_lookup()函数(默认为valuetype="glob")来匹配R中文本中的某些模式。模式将是出现一个单词与位于同一短语中任何位置的第二个单词有关。

library(quanteda)

text <- c(d1 = "apples word word word oranges", 
          d2 = "apples oranges", 
          d3 = "oranges and apples")

dict <- dictionary(list(fruits = c("apple* orange*")))

tokens(text) %>% 
  tokens_lookup(dict, valuetype = "glob") %>% 
  dfm()

将此字典从上面应用于标记化文本将产生0-1-0的结果,而我期望1-1-0。

所以我的问题是,全局模式匹配中的空格是什么,星号不应该匹配包括空格在内的所有内容吗?更一般而言,如何将d1,d2以及潜在的d3与一个相同的模式匹配?

编辑:

在正则表达式模式匹配中,这不是什么大问题。示例:

text <- c(d1 = "apples word word word oranges", 
          d2 = "apples oranges")

dict <- dictionary(list(fruits = c("apples.*oranges")))

tokens(text, what="sentence") %>%
  tokens_lookup(dict, valuetype = "regex") %>%
  dfm()
r dictionary glob quanteda
1个回答
1
投票

tokens()段上的空白,tokens_lookup()查找标记中的模式-如果该模式在字典值中包含空白,则以标记序列的形式查找。要使用全局匹配来获取两个其他特定模式之间的任何标记,可以将*指定为模式的该部分。 (从技术上讲,具有空格的模式被解析为称为“说短语”的序列。请参见?phrase。)

因此,请稍加修改您的示例:

library("quanteda")
## Package version: 2.0.1

text <- c(
  d1 = "apples word word oranges",
  d2 = "apples and oranges",
  d3 = "oranges and apples"
)

dict <- dictionary(list(fruits = c(
  "apple* * orange*",
  "apple* * * orange*"
)))

tokens(text) %>%
  tokens_lookup(dict, valuetype = "glob", exclusive = FALSE)
## Tokens consisting of 3 documents.
## d1 :
## [1] "FRUITS"
## 
## d2 :
## [1] "FRUITS"
## 
## d3 :
## [1] "oranges" "and"     "apples"

[这里,我们得到apple*的模式,后跟任何令牌之一或任何令牌中的两个,然后是orange*

这将不是拾取“橙色”后跟“苹果”,但是,因为这是相反的顺序,因此不会拾取“苹果橙色”,因为它们之间没有任何标记。 (但是您可以通过向fruits键中添加第三个值来添加该大小写,就像““ apple * orange *”。)

© www.soinside.com 2019 - 2024. All rights reserved.