【问题标题】:How to search for words in a Corpus?如何在语料库中搜索单词?
【发布时间】:2020-12-21 22:00:19
【问题描述】:

假设我有一个包含 2 列的数据框:“question_no”和“question_text” "question_no" 只是从 1 到 length(data$question_no) 并且 "question_text" 有问题。 我想对包含“按顺序”和“总结”字样的问题进行分类。 到目前为止,我已经想出了这几行代码:

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=

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

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

【问题讨论】:

  • 也许看看grep
  • question_text 条目是否可以包含除“summarize”和“in order”之外的词,即您只查找完整匹配还是部分匹配?是否要创建一个新列来指定是否满足您的条件?
  • 例如:“‘总结’第一段的第二段。”假设我有这类问题(或说明),我想定义它们是否有“总结”或“按顺序”。

标签: r tm corpus


【解决方案1】:

有了这个数据框:

   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 创建一个等于第一个参数长度的逻辑向量。它搜索原始向量中的每个元素以查看它是否包含您想要的字符串(或字符串)。请注意,我正在检查单词“summarize”和“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"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多