【问题标题】:How can I extract a word (string) and a couple of words inside a R observation?如何在 R 观察中提取一个单词(字符串)和几个单词?
【发布时间】:2020-06-10 18:50:41
【问题描述】:

这是我的 df:

Phrase               
  <chr>                 
1 I am hungry               
2 I am going to school     
3 It's raining              
4 I like talking

我想为每个观察提取一些关键词,例如(“Hungry”、“School”、“I”和“I am”),如下所示:

  Phrase               Hungry School     I `I am`
  <chr>                 <dbl>  <dbl> <dbl>  <dbl>
1 I am hungry               1      0     1      1
2 I am going to school      0      1     1      1
3 It's raining              0      0     0      0
4 I like talking            0      0     1      0

在上面的示例中,如果列名在短语内,则它可能具有数字 1,如果不在短语内,则它可能具有数字 0(或者可能是另一种提取方式)。

我尝试阅读一些类似这样的文章:https://www.r-bloggers.com/an-overview-of-keyword-extraction-techniques/,但我没有找到任何信息可以帮助我提取这些关键词。

【问题讨论】:

  • II am 相交

标签: r string extract


【解决方案1】:

我们可以用sapply遍历单词向量,应用grepl得到一个逻辑向量,然后用+转换成二进制

v1 <- c("Hungry", "School", "I", "I am")
cbind(df1, +(sapply(v1, function(v) grepl(paste0("\\b", toupper(v), 
       "\\b"), toupper(df1$Phrase)))))
#               Phrase Hungry School I I am
#1          I am hungry      1      0 1    1
#2 I am going to school      0      1 1    1
#3         It's raining      0      0 0    0
#4       I like talking      0      0 1    0

数据

df1 <- structure(list(Phrase = c("I am hungry", "I am going to school", 
"It's raining", "I like talking")), class = "data.frame", row.names = c("1", 
"2", "3", "4"))

【讨论】:

    【解决方案2】:

    您可以在每个单词上使用grepl,但需要注意,因为您可能会误报。

    Phrase <- c("I am hungry","I am going to school","It's raining ","I like talking")
    
    data.frame(phrase=Phrase,
        hungry = grepl("hungry",tolower(Phrase))*1,
        school = grepl("school",tolower(Phrase))*1,
        i = grepl("i\\s|\\si",tolower(Phrase))*1,
        iam = grepl("i am",tolower(Phrase))*1)
    
                    phrase hungry scholl i iam
    1          I am hungry      1      0 1   1
    2 I am going to school      0      1 1   1
    3        It's raining       0      0 0   0
    4       I like talking      0      0 1   0
    

    【讨论】:

      【解决方案3】:

      基础 R 解决方案:

      search_words <- c("Hungry", "School", "I", "I am")
      cbind(df1, data.frame(+(Vectorize(grepl)(search_words, df1, ignore.case = TRUE))))
      

      数据:@akrun 谢谢。

      df1 <- structure(list(Phrase = c("I am hungry", "I am going to school", 
      "It's raining", "I like talking")), class = "data.frame", row.names = c("1", 
      "2", "3", "4"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-08
        • 2021-05-07
        • 2021-10-14
        相关资源
        最近更新 更多