如何在多行中替换单个字线?

Posted

技术标签:

【中文标题】如何在多行中替换单个字线?【英文标题】:How to replace single word line in multiple lines? 【发布时间】:2018-07-03 06:49:05 【问题描述】:

我有一些字符串的数据框。有些行有一个单词,我想用空白替换。我可以检索单词,但在替换它们时我收到警告消息

警告信息:在 gsub(pattern = text[lengths(gregexpr("[[:alpha:]]+", text)) == : 参数 'pattern' 的长度 > 1 并且只使用第一个元素

只有第一个单词被替换,其余单词保持原样。我想替换数据框中的所有单个单词。

我使用的代码如下。

text <- c("Because I could not stop for Death -",
          "Word1",
          "He kindly stopped for me -",
          "Word2",
          "The Carriage held but just Ourselves - ",
          "word3",
          "and Immortality")

gsub(pattern = text[lengths(gregexpr("[[:alpha:]]+", text)) == 1], "", text)

我期待低于输出。

"Because I could not stop for Death -",
          "He kindly stopped for me -",
          "The Carriage held but just Ourselves - ",
          "and Immortality"

【问题讨论】:

你的预期输出是什么? 我添加了有问题的预期输出。 【参考方案1】:

在这里,一个简单的逻辑索引就可以解决问题,因为您要保留的单词似乎位于位置 1、3、5、... 等等,即

text[c(TRUE, FALSE)]
#[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
#[3] "The Carriage held but just Ourselves - " "and Immortality"

【讨论】:

【参考方案2】:
a=gsub("^\\w+$","",text)
[1] "Because I could not stop for Death -"    ""                                       
[3] "He kindly stopped for me -"              ""                                       
[5] "The Carriage held but just Ourselves - " ""                                       
[7] "and Immortality"   

grep("\\w",a,value = T)
[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
[3] "The Carriage held but just Ourselves - " "and Immortality"  

或者你可以简单地做

grep("\\w+\\s",text,value = T)
[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
[3] "The Carriage held but just Ourselves - " "and Immortality"  

【讨论】:

【参考方案3】:

您能否尝试关注一下,如果这对您有帮助,请告诉我。

text <- c("Because I could not stop for Death -",
          "Word1",
          "He kindly stopped for me -",
          "Word2",
          "The Carriage held but just Ourselves - ",
          "word3",
          "and Immortality")

获取 OP 所需输出的代码:

text[!grepl("[Ww]ord[0-9]+", text)] 

输出如下。

[1] "Because I could not stop for Death -"    "He kindly stopped for me -"             
[3] "The Carriage held but just Ourselves - " "and Immortality"

来自帮助页面的grepl

grepl 返回一个逻辑向量(x 的每个元素是否匹配)。

【讨论】:

以上是关于如何在多行中替换单个字线?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 eloquent/fluent 从单个查询中更新多行?

如何使用 SQL Server 中的存储过程在单个查询中插入多行

如何在单个查询中使用联接和聚合函数更新表中的多行

如何在 Designer-qt5 中推广的 PlotWidget() 上制作十字线鼠标跟踪器

如何将单个工作表中的多行(在 excel 中)转换为多个 CSV 文件

如何在 BigQuery SQL 中将字符串列拆分为多行单个单词和单词对?