本文介绍了如何在R中的单词之间替换特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一串字符.

str = c(".wow", "if.", "not.confident", "wonder", "have.difficulty", "shower")

我正在尝试替换."在带有空格的单词之间.所以它看起来像这样

I am trying to replace "." in between words with a whitespace. So it would look like this

".wow", "if.", "not confident", "wonder", "have difficulty", "shower"

首先,我尝试过

gsub("[\\w.\\w]", " ", str)
[1] "  o "            "if"              "not confident"   " onder"         
[5] "have difficulty" "sho er " 

它给了我想要的空白,但砍掉了所有的 w.然后,我尝试了

It gave me the whitespace I want, but chopped off all the w's. Then, I tried

gsub("\\w\\.\\w", " ", str)
[1] ".wow"          "if"            "no onfident"   "wonder"       
[5] "hav ifficulty" "shower."    

它保留了 w,但去掉了."前后的其他字符.

It kept the w's, but brought away other characters right before and after ".".

我也不能用这个

gsub("\\.", " ", str)
[1] " wow"             "if "              "not.confident"   "wonder"         
[5] "have.difficulty" "shower" 

因为它会带走."不在话之间.

because it will take away "." not in between words.

推荐答案

尝试

gsub('(\\w)\\.(\\w)', '\\1 \\2', str)
#[1] ".wow"            "if."             "not confident"   "wonder"         
#[5] "have difficulty" "shower"       

gsub('(?<=[^.])[.](?=[^.])', ' ', str, perl=TRUE)

或者像@rawr 建议的那样

Or as @rawr suggested

gsub('\\b\\.\\b', ' ', str, perl = TRUE)

这篇关于如何在R中的单词之间替换特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 22:19