【问题标题】:Removing double spaces删除双空格
【发布时间】:2021-05-20 21:12:17
【问题描述】:

我无法解决这个问题。我想创建一个带有每个标点符号计数的图(; - . ,)。 我有这个代码

wekto<-c("Robot, robot; Nose, nose; Robot, robot; Toes, toes; Robot, robot - touch your nose. Robot, robot - touch your toes.")
stops <- function(text){
    wekto%>%
      str_remove_all("[A-z]") %>%
        str_split(pattern = " ") %>%
            table() %>%
              as.data.frame %>%
                setNames(c("Punctuation","Count"))%>%
                  ggplot(aes(x=Punctuation,y=Count)) +
                    geom_col() +
                      coord_flip()+
                        theme_classic()+
                          theme(axis.text.y = element_text(size = 17))
}

但我希望它显示没有空格,由于双空格,这些空格被添加到我的数据框中。 我怎样才能删除它们? 我用str_removestr_replace 试过了,但它不起作用

【问题讨论】:

    标签: r regex dataframe


    【解决方案1】:

    您可以通过在setNames 之后将以下代码插入管道链来解决此问题:

    subset(Punctuation != "")
    

    或者考虑在正则表达式中添加空格:

    str_remove_all("[A-z\\s]") %>% 
      str_split("")
    

    但是,我还要注意不要使用像 A-z 这样的大小写混合正则表达式。你最终会包含比你想象的更多的字符:Ascii table

    您可能需要考虑A-Za-z\\w[:punct:] 等字符类:

    gsub("[^[:punct:]]+", "", wekto) %>% 
      str_split("") %>% 
      table(dnn = "Punctuation") %>% 
      as.data.frame(responseName = "Count") %>% 
      ggplot(aes(x=Punctuation,y=Count)) +
      geom_col() +
      coord_flip()+
      theme_classic()+
      theme(axis.text.y = element_text(size = 17))
    

    【讨论】:

    • 感谢您的帮助!并感谢您的建议:)