题
Python中是否有标准方法来titlecase a String(即单词以大写字符开头,所有剩余的壳体字符都有小写),但是留下像 and
, in
, , 和 of
低估?
解决方案
有一些问题。如果您使用拆分和加入,将忽略一些白空间字符。内置的大写和标题方法不忽略空白。
>>> 'There is a way'.title()
'There Is A Way'
如果句子以文章开头,则您不希望小写标题的第一个单词。
牢记这些:
import re
def title_except(s, exceptions):
word_list = re.split(' ', s) # re.split behaves as expected
final = [word_list[0].capitalize()]
for word in word_list[1:]:
final.append(word if word in exceptions else word.capitalize())
return " ".join(final)
articles = ['a', 'an', 'of', 'the', 'is']
print title_except('there is a way', articles)
# There is a Way
print title_except('a whim of an elephant', articles)
# A Whim of an Elephant
其他提示
使用 titlecase.py 模块!仅适用于英语。
>>> from titlecase import titlecase
>>> titlecase('i am a foobar bazbar')
'I Am a Foobar Bazbar'
有这些方法:
>>> mytext = u'i am a foobar bazbar'
>>> print mytext.capitalize()
I am a foobar bazbar
>>> print mytext.title()
I Am A Foobar Bazbar
没有小写的文章选项。您必须自己编码,可能是使用要降低的文章列表。
斯图尔特·科尔维尔(Stuart Colville)建立了一个Python港口 的 约翰·格鲁伯(John Gruber)撰写的perl脚本 将字符串转换为标题案例,但避免根据《纽约时报》风格手册中的规则来大写小词,并为几个特殊案例提供餐饮。
这些脚本的一些聪明:
他们大写了小词 如果在,, 等等,但是如果他们在输入中大写了,则将使它们失去资本化。
这些脚本假设除了第一个字符以外的大写字母的单词已经正确大写。这意味着他们将单独留下一个单词,而不是将其粘合到“ iTunes”或更糟糕的是“ iTunes”中。
他们跳过了用线点的任何单词。 “ example.com”和“ del.icio.us”将保持小写。
他们具有专门处理奇数案例的硬编码hacks,例如“ AT&T”和“ Q&A”,两者都包含小单词(AT和A),通常应该是小写。
标题的第一个和最后一句话总是大写的,因此“无害怕”之类的输入将变成“不害怕的”。
结肠后的一个小词将被大写。
您可以下载 这里.
capitalize (word)
这应该做。我得到的是不同的。
>>> mytext = u'i am a foobar bazbar'
>>> mytext.capitalize()
u'I am a foobar bazbar'
>>>
好的,如上所述,您必须进行自定义资本:
myText = u'i是一个傻瓜巴兹巴'
def xcaptilize(word):
skipList = ['a', 'an', 'the', 'am']
if word not in skipList:
return word.capitalize()
return word
k = mytext.split(" ")
l = map(xcaptilize, k)
print " ".join(l)
这输出
I am a Foobar Bazbar
Python 2.7的标题方法存在缺陷。
value.title()
将返回木匠's 当价值为木匠时助理's 助手
最好的解决方案可能是@biogeek使用Stuart Colville的Titlecase的解决方案。这是@etienne提出的相同解决方案。
not_these = ['a','the', 'of']
thestring = 'the secret of a disappointed programmer'
print ' '.join(word
if word in not_these
else word.title()
for word in thestring.capitalize().split(' '))
"""Output:
The Secret of a Disappointed Programmer
"""
标题以大写字母开头,与文章不符。
使用列表理解和三元运营商的单线
reslt = " ".join([word.title() if word not in "the a on in of an" else word for word in "Wow, a python one liner for titles".split(" ")])
print(reslt)
分解:
for word in "Wow, a python one liner for titles".split(" ")
将字符串分配到列表中,并启动for循环(在列表中综合)
word.title() if word not in "the a on in of an" else word
使用本机方法 title()
如果不是文章,则标题案例该字符串
" ".join
将列表元素与(空间)的独立器一起加入