如何删除 R 中字符串中特定长度的单词?
how to remove words of specific length in a string in R?
我想删除字符串中长度小于 3 的单词。例如我的输入是
str<- c("hello RP have a nice day")
我希望我的输出是
str<- c("hello have nice day")
请帮忙
x <- "hello RP have a nice day"
z <- unlist(strsplit(x, split=" "))
paste(z[nchar(z)>=3], collapse=" ")
# [1] "hello have nice day"
试试这个:
gsub('\b\w{1,2}\b','',str)
[1] "hello have nice day"
编辑
\b 是单词边界。如果需要删除额外的 space,将其更改为:
gsub('\b\w{1,2}\s','',str)
或者
gsub('(?<=\s)(\w{1,2}\s)','',str,perl=T)
或使用str_extract_all
提取所有长度>=3和paste
的单词
library(stringr)
paste(str_extract_all(str, '\w{3,}')[[1]], collapse=' ')
#[1] "hello have nice day"
这是一种使用 qdapRegex 包中的 rm_nchar_words
函数的方法,我与@hwnd(SO regex guru extraordinaire)合着。这里我展示删除 1-2 个字母的单词,然后删除 1-3 个字母的单词:
str<- c("hello RP have a nice day")
library(qdapTools)
rm_nchar_words(str, "1,2")
## [1] "hello have nice day"
rm_nchar_words(str, "1,3")
## [1] "hello have nice"
As qdapRegex 旨在教导这里是 S
函数将 1,2
放入量词花括号中的幕后正则表达式:
S("@rm_nchar_words", "1,2")
## "(?<![\w'])(?:'?\w'?){1,2}(?![\w'])"
我想删除字符串中长度小于 3 的单词。例如我的输入是
str<- c("hello RP have a nice day")
我希望我的输出是
str<- c("hello have nice day")
请帮忙
x <- "hello RP have a nice day"
z <- unlist(strsplit(x, split=" "))
paste(z[nchar(z)>=3], collapse=" ")
# [1] "hello have nice day"
试试这个:
gsub('\b\w{1,2}\b','',str)
[1] "hello have nice day"
编辑 \b 是单词边界。如果需要删除额外的 space,将其更改为:
gsub('\b\w{1,2}\s','',str)
或者
gsub('(?<=\s)(\w{1,2}\s)','',str,perl=T)
或使用str_extract_all
提取所有长度>=3和paste
library(stringr)
paste(str_extract_all(str, '\w{3,}')[[1]], collapse=' ')
#[1] "hello have nice day"
这是一种使用 qdapRegex 包中的 rm_nchar_words
函数的方法,我与@hwnd(SO regex guru extraordinaire)合着。这里我展示删除 1-2 个字母的单词,然后删除 1-3 个字母的单词:
str<- c("hello RP have a nice day")
library(qdapTools)
rm_nchar_words(str, "1,2")
## [1] "hello have nice day"
rm_nchar_words(str, "1,3")
## [1] "hello have nice"
As qdapRegex 旨在教导这里是 S
函数将 1,2
放入量词花括号中的幕后正则表达式:
S("@rm_nchar_words", "1,2")
## "(?<![\w'])(?:'?\w'?){1,2}(?![\w'])"