如何将句子(字符串)中的单词更改为Title Case,其中句子中的连词应保留或更改为小写字母
How to change the words in a sentence (string) to Title Case, where the conjunctions in the sentence should stay or change to lower letters
我需要知道如何将句子(字符串)中的单词更改为 Title Case,其中句子中的连词必须保留或更改为小写字母(所有单词)。
类似于 str_to_title(sentence, locale = "en")
,来自字符串库,但函数识别连词(for、and、the、from 等)。
最常见的并列连词是:for, and, nor, but, or, yet, so.
另外,重要的是单词 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"
我需要知道如何将句子(字符串)中的单词更改为 Title Case,其中句子中的连词必须保留或更改为小写字母(所有单词)。
类似于 str_to_title(sentence, locale = "en")
,来自字符串库,但函数识别连词(for、and、the、from 等)。
最常见的并列连词是:for, and, nor, but, or, yet, so.
另外,重要的是单词 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"