【问题标题】:keep words after keyword in string R在字符串 R 中保留关键字后的单词
【发布时间】:2017-02-14 16:11:25
【问题描述】:

问题:我正在使用标记器进行文本挖掘,并希望限制输入数据中字符串的长度。以下代码保留 如果包含单词,则为整个字符串。

    #create data frame with data 
    dd <- data.frame(
    text = c("hello how are you doing thank 
              you for helping me with this 
              problem","junk","junk"), stringsAsFactors = F)

   #keep string that only include term "how"
   dd <- filter(dd, grepl('how', text))

问题:如何修改代码,只保留关键字后的 N 个单词。

例如

如果 N =1 那么 dd 将包括:how are

如果 N =2 那么 dd 将包括:你好吗

如果 N =3 那么 dd 将包括:你好吗

...

如果我还在保留中包含其他单词,我需要可以工作的代码:

   #keep string that only include terms "how" and "with"
   dd <- filter(dd, grepl('how|with', text))

【问题讨论】:

  • 不是真正的正则表达式大师,但这可能会对您有所帮助:regex101.com/r/95g7yT/1
  • 如果您指定两个术语,例如 "how""with" 和 N = 3,您希望看到什么结果?另外,如果两个词之间的距离小于 3 个词,比如我们选择了"hello""are",该怎么办?
  • 1 - 使用两个术语“如何”或“与”和 N=3 我想生成:“你如何解决这个问题”。第二个术语“with”的结果只会将单词保留到字符串的末尾。 2 - 如果术语是“你好”和“是”,如果可能的话,我想保留:“你好,你好吗,谢谢”。

标签: r regex text-mining


【解决方案1】:

这是一种使用整洁的文本挖掘包的可能方法: (所以检查依赖关系...-

library(tidytext) # install.packages("tidytext")
library(tidyr)    # install.packages("tidyr")
library(dplyr)    # install.packages("dplyr")

dd <- data.frame(
  text = c("hello how are you doing thank 
              you for helping me with this 
              problem","junk","junk"), stringsAsFactors = F)

我提到scope 你关于单词水平的参数;很容易把下面的代码变成一个函数:

scope=2
dd %>%
  unnest_tokens(ngram, text, token = "ngrams", n = 1+scope) %>% 
  separate(ngram, paste("word",1:(scope+1),sep=""), sep = " ") %>% 
  filter(word1 %in% c("how","me")) 

# A tibble: 2 × 3
  word1 word2 word3
  <chr> <chr> <chr>
1   how   are   you
2    me  with  this

如果您想以字符串结尾,则必须折叠回 ngram,例如第二个示例:

scope=3
dd %>%
unnest_tokens(ngram, text, token = "ngrams", n = 1+scope) %>% 
  separate(ngram, paste("word",1:(scope+1),sep=""), sep = " ") %>% 
  filter(word1 %in% c("how"))  %>% apply(.,1,paste, collapse= " ")

[1] "how are you doing"

关于您的评论: 现在,如果您想按块(字符串)处理块(字符串),则必须通过处理显式执行此组。 举个例子:

scope=2
subsets <- 
    dd %>% 
    mutate(id=1:length(text)) %>%
    split(., .$id) 

unlist(lapply(subsets, function(dd) {
  dd %>%
  unnest_tokens(ngram, text, token = "ngrams", n = 1+scope) %>% 
  separate(ngram, paste("word",1:(scope+1),sep=""), sep = " ")  %>%
  filter(word1 %in% c("how","problem")) %>%
  apply(.,1,FUN=function(vec) paste(vec[-1],collapse=" "))
}))

           1 
"how are you" 

【讨论】:

  • 对了,推荐阅读优秀的Text Mining with R -- tidytextmining.com
  • 谢谢@Eric Lecoutre
  • 如果我用 c("how","problem") 运行 scope=2 我会收到:1 "how are you"; 2 “problem junk junk” 框架中第二行和第三行的单词包括在内。如何修改代码以分别处理一行的每个字符串? @Eric Lecoutre
  • 那么与“问题”一词相关的预期结果是什么?单独字符串“问题”或什么都没有,因为在范围方面没有任何连续的单词?另外:您对我的提案中的选项 1(单词向量)或选项 2(字符串)感兴趣吗?
  • 如果 word = “problem” 并且范围大于 1,那么什么都没有。我对选项 2(字符串)感兴趣。感谢您让我澄清。
猜你喜欢
  • 1970-01-01
  • 2014-06-04
  • 1970-01-01
  • 2020-10-28
  • 2023-02-23
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
相关资源
最近更新 更多