对于这个例子,我使用了三个包:NLP 和 openNLP(用于句子分割)和 SnowballC(用于词形还原)。我没有使用上面提到的 tokenizers 包,因为我不知道。我提到的包是 Apache OpenNLP 工具包的一部分,社区广为人知和使用。
首先,使用下面的代码安装提到的包。如果您已安装软件包,请跳至下一步:
## List of used packages
list.of.packages <- c("NLP", "openNLP", "SnowballC")
## Returns a not installed packages list
new.packages <- list.of.packages[!(list.of.packages %in% installed.packages()[,"Package"])]
## Installs new packages
if(length(new.packages))
install.packages(new.packages)
接下来,加载使用过的包:
library(NLP)
library(openNLP)
library(SnowballC)
接下来,将文本转换为字符串(NLP 封装函数)。这是必要的,因为 openNLP 包使用 String 类型。在此示例中,我使用了您在问题中提供的相同文本:
example_text <- paste0("The Boy lives in Miami and studies in the St. Martin School. ",
"The boy has a heiht of 5.7 and weights 60 Kg's. ",
"He has intrest in the Arts and crafts; and plays basketball. ")
example_text <- as.String(example_text)
#output
> example_text
The Boy lives in Miami and studies in the St. Martin School. The boy has a heiht of 5.7 and weights 60 Kg's. He has intrest in the Arts and crafts; and plays basketball.
接下来,我们使用 openNLP 包生成句子注释器,通过句子检测器计算注释:
sent_annotator <- Maxent_Sent_Token_Annotator()
annotation <- annotate(example_text, sent_annotator)
接下来,通过文中做的注释,我们可以提取句子:
splited_text <- example_text[annotation]
#output
splited_text
[1] "The Boy lives in Miami and studies in the St. Martin School."
[2] "The boy has a heiht of 5.7 and weights 60 Kg's. "
[3] "He has intrest in the Arts and crafts; and plays basketball. "
最后,我们使用了支持英语的 SnowballC 包的 wordStem 函数。此函数将一个词或词向量简化为其部首(通用基本形式)。接下来,我们使用基础包R的grep函数来查找包含我们要查找的关键字的句子:
stemmed_keyword <- wordStem ("study", language = "english")
sentence_index<-grep(stemmed_keyword, splited_text)
#output
splited_text[sentence_index]
[1] "The Boy lives in Miami and studies in the St. Martin School."
注意
请注意,我已更改您从 **“... 圣马丁学校”提供的示例文本。 ** 到 ** “……圣马丁学校。” **。如果字母“s”保持小写,句子检测器将理解“st”中的标点符号。是一个终点。分割后的向量如下:
> splited_text
[1] "The Boy lives in Miami and studies in the st." "Martin School."
[3] "The boy has a heiht of 5.7 and weights 60 Kg's." "He has intrest in the Arts and crafts; and plays basketball."
因此,当检查此向量中的关键字时,您的输出将是:
> splited_text[sentence_index]
[1] "The Boy lives in Miami and studies in the st."
我也测试了上面提到的分词器包,也有同样的问题。因此,请注意这是 NLP 注释任务中的一个开放问题。但是,上述逻辑和算法可以正常工作。
我希望这会有所帮助。