Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 标题为字符串加上异常_Python_String_Title Case - Fatal编程技术网

Python 标题为字符串加上异常

Python 标题为字符串加上异常,python,string,title-case,Python,String,Title Case,Python中是否有一种标准的方法来命名字符串(即,单词以大写字符开头,所有剩余的大小写字符都有小写),但留下诸如和,中的,以及中的等文章,这些方法有: >>> mytext = u'i am a foobar bazbar' >>> print mytext.capitalize() I am a foobar bazbar >>> print mytext.title() I Am A Foobar Bazbar 没有小写的冠词选项。您

Python中是否有一种标准的方法来命名字符串(即,单词以大写字符开头,所有剩余的大小写字符都有小写),但留下诸如
中的
,以及
中的
等文章,这些方法有:

>>> mytext = u'i am a foobar bazbar'
>>> print mytext.capitalize()
I am a foobar bazbar
>>> print mytext.title()
I Am A Foobar Bazbar
没有小写的冠词选项。您必须自己编写代码,可能需要使用您想要降低的文章列表

capitalize (word)
这应该可以。我的理解不同

>>> mytext = u'i am a foobar bazbar'
>>> mytext.capitalize()
u'I am a foobar bazbar'
>>>
好的,正如上面回复中所说,您必须自定义大写:

mytext=u'i a 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
标题以大写单词开头,与文章不匹配。

使用模块!只适用于英语

>>> from titlecase import titlecase
>>> titlecase('i am a foobar bazbar')
'I Am a Foobar Bazbar'

GitHub:

这方面存在一些问题。如果使用拆分和联接,将忽略某些空白字符。内置的大写和标题方法不会忽略空白

>>> '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
当然可以将字符串转换为标题大小写,但避免根据《纽约时报文体手册》中的规则将小词大写,同时也避免了一些特殊情况

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

  • 它们将诸如if、in、of、on等小词大写,但如果它们在输入中被错误地大写,它们将取消大写

  • 脚本假定第一个字符以外的大写字母的单词已经正确大写。这意味着他们将把像“iTunes”这样的词单独留下,而不是把它弄成“iTunes”或者更糟的“iTunes”

  • 他们跳过任何带有线点的单词;“example.com”和“del.icio.us”将保持小写

  • 他们有专门处理奇怪情况的硬编码黑客,如“AT&T”和“Q&A”,它们都包含通常应为小写的小词(AT和A)

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

  • 冒号后面的小字将大写


您可以下载它。

Python2.7的title方法有一个缺陷

value.title()
当值为Carpenter'SAssistant时,将返回Carpenter'SAssistant


最好的解决方案可能是使用Stuart Colville的滴定酶从@BioGeek获得的解决方案。这与@Etienne提出的解决方案相同。

使用列表理解和三元运算符的一行

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)
细分:

用于“Wow,一个python标题单行程序”中的单词。split(“”
将字符串拆分为一个列表,并启动for循环(在列表中)

word.title()如果单词不在“a on in of an”else单词中
使用本机方法
title()
对字符串的大小写进行标题(如果字符串不是文章)


”.join
使用(空格)分隔符连接列表元素

没有考虑的一个重要情况是首字母缩略词(如果您明确将首字母缩略词作为例外提供,python titlecase解决方案可以处理首字母缩略词)。我宁愿简单地避免下套管。通过这种方法,已经是大写的首字母缩略词仍然是大写的。以下代码是对dheerosaur最初提供的代码的修改

# This is an attempt to provide an alternative to ''.title() that works with 
# acronyms.
# There are several tricky cases to worry about in typical order of importance:
# 0. Upper case first letter of each word that is not an 'minor' word.
# 1. Always upper case first word.
# 2. Do not down case acronyms
# 3. Quotes
# 4. Hyphenated words: drive-in
# 5. Titles within titles: 2001 A Space Odyssey
# 6. Maintain leading spacing
# 7. Maintain given spacing: This is a test.  This is only a test.

# The following code addresses 0-3 & 7.  It was felt that addressing the others 
# would add considerable complexity.


def titlecase(
    s,
    exceptions = (
        'and', 'or', 'nor', 'but', 'a', 'an', 'and', 'the', 'as', 'at', 'by',
        'for', 'in', 'of', 'on', 'per', 'to'
    )
):
    words = s.strip().split(' ')
        # split on single space to maintain word spacing
        # remove leading and trailing spaces -- needed for first word casing

    def upper(s):
        if s:
            if s[0] in '‘“"‛‟' + "'":
                return s[0] + upper(s[1:])
            return s[0].upper() + s[1:]
        return ''

    # always capitalize the first word
    first = upper(words[0])

    return ' '.join([first] + [
        word if word.lower() in exceptions else upper(word)
        for word in words[1:]
    ])


cases = '''
    CDC warns about "aggressive" rats as coronavirus shuts down restaurants
    L.A. County opens churches, stores, pools, drive-in theaters
    UConn senior accused of killing two men was looking for young woman
    Giant asteroid that killed the dinosaurs slammed into Earth at ‘deadliest possible angle,’ study reveals
    Maintain given spacing: This is a test.  This is only a test.
'''.strip().splitlines()

for case in cases:
    print(titlecase(case))
运行时,会产生以下结果:

CDC Warns About "Aggressive" Rats as Coronavirus Shuts Down Restaurants L.A. County Opens Churches, Stores, Pools, Drive-in Theaters
UConn Senior Accused of Killing Two Men Was Looking for Young Woman
Giant Asteroid That Killed the Dinosaurs Slammed Into Earth at ‘Deadliest Possible Angle,’ Study Reveals
Maintain Given Spacing: This Is a Test.  This Is Only a Test.

那不是我想要的。我想得到“我是一个Foobar Bazbar”@Yassin Ezbakhe:编辑我的答案,这应该对你有用。文章列表可以很容易地从任何dictionarytitlecase.py lowercases文章中提取。如果要转换的字符串中的任何位置包含数字,则titlecase模块不起作用。@特洛伊数字问题似乎已解决,或者我没有碰到您的边缘大小写。例如:滴定酶('1-4-2')->'1-4-2'。现在titlecase('1one')->'1one',但是'1one'。title()->'1one'。虽然后一种情况是边缘情况,我不确定“1”是正确的标题。我也没有足够的精力去拿我的语法书。在“321 A百老汇大街”的案例中,我得“321 A百老汇大街”才行。使用上面dheerosaur提出的解决方案产生了“321 A百老汇大街”。同样好的是,它使标题中的首字母缩略词保持不变“创新TIaSR的开发”变为“创新TIaSR的开发”。为什么需要
re
?“<代码>”、“拆分< /代码>”函数也一样。@ WiZigWiZ4:<代码> STR.SPLIG/<代码>不考虑邻接空间。代码>重新拆分
保留空格。所以,这个函数不会占用任何空间。@ dHeReSoaR我认为<>代码>“SPLITE()/<代码>没有考虑它们,而是“代码>”“拆分”(“”)。你的代码不能正确地用于<代码> TILLYI,除了(一个大象的突发奇想,文章) CASE。您可以在异常
过滤条件中使用
word.lower()来修复它。@dheerosaur我正在寻找一种方法,不仅可以将文章后面的单词大写,还可以将数字后面的单词大写。你能在你的回答中补充一点来说明这一点吗?例如,
2001《太空漫游》
应返回
2001《太空漫游》
,其中
a
在数字后大写。提前谢谢。
CDC Warns About "Aggressive" Rats as Coronavirus Shuts Down Restaurants L.A. County Opens Churches, Stores, Pools, Drive-in Theaters
UConn Senior Accused of Killing Two Men Was Looking for Young Woman
Giant Asteroid That Killed the Dinosaurs Slammed Into Earth at ‘Deadliest Possible Angle,’ Study Reveals
Maintain Given Spacing: This Is a Test.  This Is Only a Test.