我需要知道如何将句子(字符串)中的单词更改为标题大小写,其中句子中的连词必须保留或更改为小写字母(所有单词)。
与字符串库中的
str_to_title(sentence, locale = "en")
类似,但其中函数可识别连词(for、and、the、from 等)。
最常见的并列连词是:for、and、nor、but、or、yet 等。
此外,重要的是单词 the 保持小写,而不是 when 是第一个单词。第一个和最后一个单词的第一个字母应始终大写。
例如:
sentence = "THE LOVer Tells OF THE rose in HIS HEART"
我想把字符串句子改为:
"The Lover Tells of the Rose in His Heart"
这称为 Title Case。
如有任何帮助,我们将不胜感激
这个解决方案怎么样? 我从编程中找出了你的问题。
sentence <- "THE LOVer Tells OF THE rose in HIS HEART"
require(stringr)
words <- unlist(strsplit(sentence,' ')) %>% tolower()
conjunctions <- c('for', 'and', 'nor', 'but', 'or', 'yet','the','of','in')
for(i in seq_len(length(words))){
if(i==1 & words[i] %in% conjunctions){
words[i] <- str_to_title(words[i])
} else if (!words[i] %in% conjunctions) {
words[i] <- str_to_title(words[i])
}
}
words
result <- paste(words, collapse=' ')
result
tolower
。str_to_title
。paste
将单词变成句子。result
将是
[1] "The Lover Tells of the Rose in His Heart"
使用
library(tools)
加载包,使用toTitleCase函数转换字符串toTitleCase(sentence)
,就完成了!请注意,此功能仅适用于英语,不适用于任何其他语言。