如何在 R 中的字符串中的每个单词周围添加引号?
How to add quotes around each word in a string in R?
我有一个字符串:
words<-"Monday, Tuesday, Wednesday, Thursday,Friday"
我只需要给每个单词加上引号:
"Monday", "Tuesday", "Wednesday", "Thursday","Friday"
得到五个字符串的长度。
我知道有很多 post 关于这个主题,但我没有在 R 中找到任何相关内容。
非常感谢。
我们可以将单词按 ,
拆分以获得 list
输出。我们遍历 sapply
, dQuote
元素,然后 paste
与 toString
一起循环,后者是 paste(..., collapse=', ')
.
的包装器
sapply(strsplit(words, '[, ]+'), function(x) toString(dQuote(x)))
#[1] "“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”"
如果我们需要更改花哨的引号,请在 dQuote
中添加 FALSE
sapply(strsplit(words, '[, ]+'), function(x) toString(dQuote(x, FALSE)))
strsplit 按逗号拆分字符串,sub 删除空格。
paste(dQuote(sub(" ","",unlist(strsplit(words,split = ",")))),collapse = ", ")
[1] "“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”"
使用gsub
words<-"Monday, Tuesday, Wednesday, Thursday,Friday"
cat(gsub("(\w+)", '"\1"', words))
# "Monday", "Tuesday", "Wednesday", "Thursday","Friday"
吻....
cat(gsub("\b", '"', words, perl=T))
#"Monday", "Tuesday", "Wednesday", "Thursday","Friday"
\b
称为单词边界,它匹配单词字符 (A-Z,a-z,_,0-9) 和非单词字符(不是 A -Za-z0-9_) 或者反之亦然..
我有一个字符串:
words<-"Monday, Tuesday, Wednesday, Thursday,Friday"
我只需要给每个单词加上引号:
"Monday", "Tuesday", "Wednesday", "Thursday","Friday"
得到五个字符串的长度。
我知道有很多 post 关于这个主题,但我没有在 R 中找到任何相关内容。
非常感谢。
我们可以将单词按 ,
拆分以获得 list
输出。我们遍历 sapply
, dQuote
元素,然后 paste
与 toString
一起循环,后者是 paste(..., collapse=', ')
.
sapply(strsplit(words, '[, ]+'), function(x) toString(dQuote(x)))
#[1] "“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”"
如果我们需要更改花哨的引号,请在 dQuote
FALSE
sapply(strsplit(words, '[, ]+'), function(x) toString(dQuote(x, FALSE)))
strsplit 按逗号拆分字符串,sub 删除空格。
paste(dQuote(sub(" ","",unlist(strsplit(words,split = ",")))),collapse = ", ")
[1] "“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”"
使用gsub
words<-"Monday, Tuesday, Wednesday, Thursday,Friday"
cat(gsub("(\w+)", '"\1"', words))
# "Monday", "Tuesday", "Wednesday", "Thursday","Friday"
吻....
cat(gsub("\b", '"', words, perl=T))
#"Monday", "Tuesday", "Wednesday", "Thursday","Friday"
\b
称为单词边界,它匹配单词字符 (A-Z,a-z,_,0-9) 和非单词字符(不是 A -Za-z0-9_) 或者反之亦然..