【问题标题】:Removing Duplicate Words Among Multiple Strings Across a Single Vector in R在R中的单个向量中删除多个字符串中的重复单词
【发布时间】:2021-02-25 17:50:55
【问题描述】:

我有一个由多个字符串组成的向量(在 R 中):

vec <- c("the cat the cat ran up the tree tree", "the dog ran up the up the tree", 
         "the squirrel squirrel ran up the tree")

我需要清除每个单独字符串中的重复单词。

期望的输出:

"the cat ran up the tree"
"the dog ran up the tree"
"the squirrel ran up the tree"

我已经尝试过以下解决方案:Removing duplicate words in a string in R。但是,这只会将我的多个字符串合并为一个复杂的字符串。

【问题讨论】:

  • 我想对此投赞成票(这是一个有助于增加知识库的有用答案),但我不能。

标签: r text nlp duplicates


【解决方案1】:

我们可以用gsub来匹配两组词,一个词重复

gsub("((\\w+\\s+\\w+\\s?)|(\\w+\\s+))\\1+", "\\1", vec)
#[1] "the cat ran up the tree"    
#[2]  "the dog ran up the tree"     
#[3] "the squirrel ran up the tree"

【讨论】:

  • 你能推荐一个涵盖这些规则的正则表达式教程吗?
  • @EnglishmanBob 也许this 会给出一些类似的语法解释
猜你喜欢
  • 2021-12-30
  • 2013-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 1970-01-01
相关资源
最近更新 更多