Python中标题的正确大写形式

8
我正在寻找一个库,可以正确地将给定的字符串大写,并假设它是一个标题。我知道有string.title(),但它会大写每个单词,而不仅仅是应该大写的那些单词。有人知道任何库吗?
以下是标题中不应大写的词的示例:
- 介词(in, from等) - 冠词(a, an, the) - van - de

5
“开货车回家”应该如何大写? - Steven Rumbalski
开车回家 - Raz
2个回答

19

要搜索的术语是“titlecase”。 第一个结果 titlecase 软件包

$ pip install titlecase
...
$ python
...
>>> from titlecase import titlecase
>>> titlecase('the spam and eggs')
'The Spam and Eggs'

0
如果您想将字符串大写,但只想大写某些单词,您需要在某个列表中指定不想大写的单词,然后执行类似以下操作:
excluded_words = ["words","you","want","excluded"]

titled = [word.capitalize() if word not in excluded_words else word 
           for word in title.split(" ")]

只有在您希望使用一些奇怪的(或未实现的)标准时,才需要这样做。如果您能找到一个符合您要求标准的包,则应使用该包。


1
使用集合代替列表:excluded_words = {"words","you","want","excluded"}。集合使用哈希表,非常高效。 - sleblanc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接