我正在寻找一个库,可以正确地将给定的字符串大写,并假设它是一个标题。我知道有string.title(),但它会大写每个单词,而不仅仅是应该大写的那些单词。有人知道任何库吗?
以下是标题中不应大写的词的示例:
- 介词(in, from等) - 冠词(a, an, the) - van - de
以下是标题中不应大写的词的示例:
- 介词(in, from等) - 冠词(a, an, the) - van - de
要搜索的术语是“titlecase”。 第一个结果 是 titlecase
软件包。
$ pip install titlecase
...
$ python
...
>>> from titlecase import titlecase
>>> titlecase('the spam and eggs')
'The Spam and Eggs'
excluded_words = ["words","you","want","excluded"]
titled = [word.capitalize() if word not in excluded_words else word
for word in title.split(" ")]
只有在您希望使用一些奇怪的(或未实现的)标准时,才需要这样做。如果您能找到一个符合您要求标准的包,则应使用该包。
excluded_words = {"words","you","want","excluded"}
。集合使用哈希表,非常高效。 - sleblanc