Python 包含异常词列表的标题大小写
我正试图想出一些能“命名”一串单词的东西。它应该大写字符串中的所有单词,除非给定的单词不作为参数大写。但不管发生什么,它都会大写第一个单词。我知道如何大写每个单词,但我不知道如何不大写例外。不知从哪里开始,在谷歌上找不到太多Python 包含异常词列表的标题大小写,python,python-3.x,Python,Python 3.x,我正试图想出一些能“命名”一串单词的东西。它应该大写字符串中的所有单词,除非给定的单词不作为参数大写。但不管发生什么,它都会大写第一个单词。我知道如何大写每个单词,但我不知道如何不大写例外。不知从哪里开始,在谷歌上找不到太多 def titlemaker(title, exceptions): return ' '.join(x[0].upper() + x[1:] for x in title.split(' ')) 或 但我发现它会在撇号后大写字母,所以我不认为我应该使用它
def titlemaker(title, exceptions):
return ' '.join(x[0].upper() + x[1:] for x in title.split(' '))
或
但我发现它会在撇号后大写字母,所以我不认为我应该使用它。
关于我应该如何考虑例外情况的任何帮助都会很好
例子:标题制作者(“一个人和他的狗”,“一个和”)应该返回“一个人和他的狗”
def titlemaker(title,exceptions):
exceptions = exceptions.split(' ')
return ' '.join(x.title() if nm==0 or not x in exceptions else x for nm,x in enumerate(title.split(' ')))
titlemaker('a man and his dog','a and') # returns "A Man and His Dog"
上面假设输入字符串和异常列表的情况相同(与您的示例中的情况相同),但在诸如“titlemaker”(“一个人和他的狗”,“a和”)之类的问题上会失败。如果他们的情况好坏参半的话
def titlemaker(title,exceptions):
exceptionsl = [x.lower() for x in exceptions.split(' ')]
return ' '.join(x.title() if nm==0 or not x.lower() in exceptions else x.lower() for nm,x in enumerate(title.split(' ')))
titlemaker('a man and his dog','a and') # returns "A Man and His Dog"
titlemaker('a man AND his dog','a and') # returns "A Man and His Dog"
titlemaker('A Man And His DOG','a and') # returns "A Man and His Dog"
试试这个:
def titleize(text, exceptions):
exceptions = exceptions.split()
text = text.split()
# Capitalize every word that is not on "exceptions" list
for i, word in enumerate(text):
text[i] = word.title() if word not in exceptions or i == 0 else word
# Capitalize first word no matter what
return ' '.join(text)
print titleize('a man and his dog', 'a and')
A Man and His Dog
输出:
def titleize(text, exceptions):
exceptions = exceptions.split()
text = text.split()
# Capitalize every word that is not on "exceptions" list
for i, word in enumerate(text):
text[i] = word.title() if word not in exceptions or i == 0 else word
# Capitalize first word no matter what
return ' '.join(text)
print titleize('a man and his dog', 'a and')
A Man and His Dog
可能重复,看一种重复,我看到了那篇文章,但它没有显示任何关于有两个参数的函数的内容。他还一直使用集合列表,我希望能够写出哪些我不想大写。
def title\u除了(s,例外)
似乎有两个输入参数:-),因为您已经枚举了文本
,为什么不在列表理解中包含条件或i==0
,以消除其下一行中额外的title()
?完成。谢谢你@floydn!为什么不在最后一个字符串上直接调用title呢?@PeterWood可能是。但是有很多方法可以做到这一点,我只是选择了一个来回答这个问题。无论如何,谢谢。结尾的.title()不是撤销了异常吗?它看起来像是将文本拆分成单词,将带有非异常标题大小写的单词连接起来,然后将.title()应用于结果字符串,该字符串将对所有单词(包括异常)进行大小写。@GarlandPope我相信你是对的。我把它改为finally call而不是,这样第一个字符总是大写。