用例外标识字符串

在Python中是否有一种标准的方法来标记一个字符串(即单词以大写字母开头,所有剩余的套接字符都是小写的)但是留下像
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制作了一个由John Gruber编写的Perl脚本的Python端口,用于将字符串转换为标题案例,但避免根据“纽约时报手册”的规则对小词进行大写,以及为几种特殊情况提供服务。 这些脚本的一些聪明之处: 它们将if,in,of,on等小词组成大写,但如果它们在输入中被错误地大写,则会将它们取消资本化。 脚本假定具有除第一个字符以外的大写字母的单词已经正确大写。这意味着他们会单独留下像“iTunes”这样的词,而不是将其分为“ITunes”或更糟糕的“Itunes”。 他们用线点跳过任何单词; “example.com”和“del.icio.us”将保持小写。 他们有专门处理奇怪情况的硬编码黑客,比如“AT& T”和“Q& A”,两者都包含通常应该是小写的小词(at和a)。 标题的第一个和最后一个字总是大写的,所以诸如“没什么可害怕的”这样的输入将变成“没什么可害怕的”。 结肠后的一个小词将被大写。 您可以在这里下载。     
capitalize (word)
这应该做。我有不同的看法。
>>> mytext = u'i am a foobar bazbar'
>>> mytext.capitalize()
u'I am a foobar bazbar'
>>>
好的,如上面的回复中所说,你必须自定义大写: mytext =你是一个foobar bazbar'
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()
当价值是Carpenter的助手时,将返回Carpenter'S Assistant 最好的解决方案可能来自@BioGeek使用Stuart Colville的标题。这与@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
将列表元素与(空格)的分隔符连接起来     

要回复问题请先登录注册