如何在语料库中搜索单词?

问题描述

假设我有一个包含2列的数据框:“ question_no”和“ question_text” “ question_no”仅从1到length(data$question_no),“ question_text”有问题。 我想对包含单词“ in order”和“ summary”的问题进行分类。 到目前为止,我已经提出了以下几行代码

questions<-Corpus(VectorSouce(data$question_text))
questions<-tm_map(questions,tolower)
questions<-tm_map(questions,stripwhiteSpace)
spesificQuestion<- ifelse(Corpus=="in order"|Corpus=="summarize",pquestions,others=

我知道这是一组非常糟糕的代码,我只是想表明我的意图。

我应该怎么做才能从语料库中选择某些单词?

解决方法

使用此数据框:

   df <- data.frame(
   question_no = c(1:6),question_text = c("put these words in order","summarize the  paper","nonsense","summarize the story","put something in order","nonsense")
   )

    question_no            question_text
       1             put these words in order
       2             summarize the paper
       3             nonsense
       4             summarize the story
       5             put something in order
       6             nonsense

您可以尝试...

     library(stringr)
     library(dplyr)
     mutate (df,condition_met = if_else(str_detect(df$question_text,"\\bsummarize\\b|\\bin order\\b"),"Yes","No"))

哪个生产...

  question_no            question_text         condition_met
       1         put these words in order           Yes
       2         summarize the paper                Yes
       3         nonsense                           No
       4         summarize the story                Yes
       5         put something in order             Yes
       6         nonsense                           No

stringr::str_detect创建一个等于第一个参数长度的逻辑向量。它搜索原始向量中的每个元素,以查看它是否包含所需的字符串(或多个字符串)。请注意,我正在检查单词“ summaryize”和单词“ in order”,以避免匹配“ un-summarize”之类的内容。如果对您而言无关紧要,您可以将匹配的字符串转换为".*summarize.*|.*in order.*"。使用if_else可以将TRUEFALSE转换为所需的内容。在这种情况下,我做了“是”和“否”。

dplyr::mutate创建一个新列,命名为您想要的名称。保留TRUE和FALSE的值将使您看到多少或多少比例的条目包含您感兴趣的字符串。如果这是您想要的,则取出if_else参数,即... >

     mutate (df,condition_met = str_detect(df$question_text,"\\bsummarize\\b|\\bin order\\b"))