【问题标题】:Check which rows with each word in a string are capitalised and space separated检查字符串中每个单词的哪些行大写并用空格分隔
【发布时间】:2019-11-14 04:12:49
【问题描述】:

我有一列包含如下所示的值字符串

a=["iam best in the world" "you are awesome" ,"Iam Good"]

我需要检查字符串中每个单词的哪些行是小写并用空格分隔。

我知道如何将它们转换为大写和空格分隔,但我需要找到哪些行是小写和空格分隔的。

我尝试过使用

grepl("\\b([a-z])\\s([a-z])\\b",aa, perl =  TRUE)

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    我们可以尝试将grepl\b[a-z]+(?:\\s+[a-z]+)*\b 模式一起使用:

    matches = a[grepl("\\b[a-z]+(?:\\s+[a-z]+)*\\b", a$some_col), ]
    matches
    
      v1              some_col
    1  1 iam best in the world
    2  2       you are awesome
    

    数据:

    a <- data.frame(v1=c(1:3),
                    some_col=c("iam best in the world", "you are awesome", "Iam Good"))
    

    使用的正则表达式匹配一个全小写单词,后跟一个空格和另一个全小写单词,后者重复零次或多次。请注意,我们在模式周围放置了单词边界,以确保我们不会从以大写字母开头的单词中获得错误的标志匹配。

    【讨论】:

      【解决方案2】:
      x <- c("iam best in the word ", "you are awesome", "Iam Good")
      

      在这里我做了一些不同的事情,首先我用空格分隔然后我检查是否是小写。因此,输出是每个短语的列表,只有小写单词被空格分隔。

      sapply(strsplit(x, " "), function(x) {
        x[grepl("^[a-z]", x)]
      })
      

      【讨论】:

        【解决方案3】:

        另一个想法是使用stringi包中的stri_trans_totitle

        a[!!!stringi::stri_trans_totitle(as.character(a$some_col)) == a$some_col,]
        
        #  v1              some_col
        #1  1 iam best in the world
        #2  2       you are awesome
        

        【讨论】:

          【解决方案4】:

          我们可以将列转换为小写并与实际值进行比较。使用@Tim 的数据

          a[tolower(a$some_col) == a$some_col, ]
          
          #  v1              some_col
          #1  1 iam best in the world
          #2  2       you are awesome
          

          如果我们还需要检查空间,我们可以添加另一个条件 grepl

          a[tolower(a$some_col) == a$some_col & grepl("\\s+", a$some_col), ]
          

          【讨论】:

          • 呵呵呵呵...不过话说回来,伟大的思想都一样;)
          【解决方案5】:

          我们可以使用filter

          library(dplyr)
          a %>%
             filter(tolower(some_col) == some_col)
          #   v1              some_col
          #1  1 iam best in the world
          #2  2       you are awesome
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-12-01
            • 2021-05-21
            • 1970-01-01
            • 2022-08-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多