用异常来标记字符串

yas*_*sin 85 python string title-case

有没有在Python的标准方式标题字符的字符串(即词开始大写字符,所有剩余的套管字符有小写),但像离开的文章and,inof小写?

dhe*_*aur 147

这有一些问题.如果使用拆分和连接,则会忽略某些空白字符.内置的大写和标题方法不会忽略空格.

>>> 'There     is a way'.title()
'There     Is A Way'
Run Code Online (Sandbox Code Playgroud)

如果一个句子以文章开头,则不希望标题的第一个单词为小写.

记住这些:

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
Run Code Online (Sandbox Code Playgroud)

  • 为"以文章开头的句子"案例+1 (5认同)

Eti*_*nne 48

使用titlecase.py模块!仅适用于英语.

>>> from titlecase import titlecase
>>> titlecase('i am a foobar bazbar')
'I Am a Foobar Bazbar'
Run Code Online (Sandbox Code Playgroud)


nos*_*klo 20

有这些方法:

>>> mytext = u'i am a foobar bazbar'
>>> print mytext.capitalize()
I am a foobar bazbar
>>> print mytext.title()
I Am A Foobar Bazbar
Run Code Online (Sandbox Code Playgroud)

没有小写文章选项.你必须自己编写代码,可能是使用你想要降低的文章列表.


Bio*_*eek 12

Stuart Colville制作了一个由John Gruber编写的Perl脚本的Python端口,用于将字符串转换为标题案例,但避免根据"纽约时报手册"的规则对小词进行大写,以及为几种特殊情况提供服务.

这些脚本的一些聪明之处:

  • 它们将if,in,of,on等小词组成大写,但如果它们在输入中被错误地大写,则会将它们取消资本化.

  • 脚本假定具有除第一个字符以外的大写字母的单词已经正确大写.这意味着他们会单独留下像"iTunes"这样的词,而不是将其分为"ITunes"或更糟糕的"Itunes".

  • 他们用线点跳过任何单词; "example.com"和"del.icio.us"将保持小写.

  • 他们有专门处理奇怪案件的硬编码黑客,比如"AT&T"和"Q&A",两者都包含通常应该小写的小词(at和a).

  • 标题的第一个和最后一个字总是大写的,所以诸如"没什么可害怕的"这样的输入将变成"没什么可害怕的".

  • 结肠后的一个小词将被大写.

你可以在这里下载.