作为一个R新手,通过使用quanteda,我试图找到一个单词顺序出现在一个句子中另一个单词之前的实例。更具体地说,我正在寻找“投资者”一词位于摩洛哥和尼日利亚之间缔结的一项国际条约构成的语料库中“应”一词之前的某个地方的例子(案文见此处:https://edit.wti.org/app.php/document/show/bde2bcf4-e20b-4d05-a3f1-5b9eb86d3b3b)。
问题是,有时这两个词之间有多个单词。例如,有时它被写成“投资者和投资应当”。我试着在这个网站上应用类似的解决方案。当我在(Keyword in context (kwic) for skipgrams?)上尝试解决方案并运行以下代码时:
kwic(corpus_mar_nga, phrase("investors * shall"))我得到了0的观察,因为这只算在“投资者”和“应该”之间只有一个词的情况下。
当我遵循(Is it possible to use kwic function to find words near to each other?)上提供的另一个解决方案并运行以下代码时:
toks <- tokens(corpus_mar_nga)
toks_investors <- tokens_select(toks, "investors", window = 10)
kwic(toks_investors, "shall")当“投资者”也出现在“将”之后时,我得到了一些例子,这从根本上改变了上下文,因为在这种情况下,句子的主语是不同的。
最后,除了“投资者应当”的情况外,我也应该得到,例如,它是“投资者,他们的投资和东道国当局应该”的例子,但我不能用上面的代码。
有人能给我一个解决这个问题的办法吗?
非常感谢,提前!
发布于 2020-11-21 09:37:08
问得好。这里有两种方法,一种依赖于语料库文本上的正则表达式,另一种使用(正如@Kohei_Watanabe在注释中建议的那样)使用tokens_select()窗口。
首先,创建一些示例文本。
library("quanteda")
## Package version: 2.1.2
# sample text
txt <- c("The investors and their supporters shall do something.
Shall we tell the investors? Investors shall invest.
Shall someone else do something?")现在把它重塑成句子,因为你的搜索发生在句子中。
# reshape to sentences
corp <- txt %>%
corpus() %>%
corpus_reshape(to = "sentences")方法1使用正则表达式。我们在“投资者”之前添加一个边界(\\b),.+在“投资者”和“将”之间表示一个或多个字符。(这不会捕获换行符,但是corpus_reshape(x, to = "sentences")会删除它们。)
# method 1: regular expressions
corp$flag <- stringi::stri_detect_regex(corp, "\\binvestors.+shall",
case_insensitive = TRUE
)
print(corpus_subset(corp, flag == TRUE), -1, -1)
## Corpus consisting of 2 documents and 1 docvar.
## text1.1 :
## "The investors and their supporters shall do something."
##
## text1.2 :
## "Investors shall invest."第二种方法使用带有非对称窗口的tokens_select()和kwic()。首先,我们选择包含“投资者”的所有文档(它们是句子),但先丢弃令牌,然后保留所有令牌。之后的1000个代币就足够了。然后,应用kwic(),在这里我们保留所有的上下文词,但是关注于“后”一词,顾名思义,这个词必须在后面,因为第一个词是“投资者”。
# method 2: tokens_select()
toks <- tokens(corp)
tokens_select(toks, "investors", window = c(0, 1000)) %>%
kwic("shall", window = 1000)
##
## [text1.1, 5] investors and their supporters | shall | do something.
## [text1.3, 2] Investors | shall | invest.选择取决于什么最适合你的需要。
https://stackoverflow.com/questions/64931046
复制相似问题