【问题标题】:replace word in character sentence in R替换R中字符句子中的单词
【发布时间】:2020-11-24 13:34:06
【问题描述】:

好的,如何更改长度为 1 的字符向量中的单词? 更具体地说,我显然在长度为 1 的字符向量中有句子“我想要这本书”,我想用“那个”替换“这个”这个词,然后找出其中存在多少个“那个”句子(其中 ofc 将为 1)。 问题; 我该怎么做呢? 我是否必须更改向量中的某些内容才能使用其他代码?就像让每个单词都成为一个独特的角色? 我想用最简单的方法做到这一点,如果可能的话,避免令人困惑的编码...... 谢谢大家!

【问题讨论】:

  • stringr 包有一些方便的东西,比如 str_replace_all()、str_extract()。基本包包括 grepl()、strsplit()、substr()、nchar()... 之类的东西。

标签: r vector character


【解决方案1】:

要计数,您可以使用:

stringr::str_count("I want this book", "this")

并替换:

stringr::str_replace("I want this book", "this", "that")

或在基础R中

gsub("this", "that", "I want this book", fixed = TRUE)

【讨论】:

    【解决方案2】:

    以下内容满足您的要求。

    myword <- "this is just that whatever mate this is it"
    # 1. replace this with that
    result <- gsub("this", "that", myword)
    #2. count the "that" occurrences
    length(unlist(strsplit(result, "that")))-1
    

    stringr

    library(stringr)
    str_count(result, "that")
    > str_count(result, "that")
    [1] 3
    > result
    [1] "that is just that whatever mate that is it"
    

    【讨论】:

      猜你喜欢
      • 2017-07-29
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多