📌  相关文章
📜  在Python中将字符串转换为标题大小写

📅  最后修改于: 2020-07-24 04:54:09             🧑  作者: Mango

标题案例是一种写作风格,用于文章,书籍,电影和其他作品的标题。标题大写的规则是:

1)始终大写第一个单词。
2)大写所有单词,但以下部分除外:

  • 文章– a,an,the
  • 协调连词–和,但是,对于,也没有,或如此,到目前为止
  • 简短介词–上,下,上等

例子:

输出 : The quick brown fox jumps over the lazy dog.
输出 : The Quick Brown Fox Jumps over the Lazy Dog.

输出 : A tale of two cities
输出 : A Tale of Two Cities

算法:

  1. 列出所有必须小写的单词。
  2. 对于输入中的每个单词,请检查它是否在上面的列表中。
  3. 如果是,则忽略该单词,如果否,则将其首字母大写。

上述算法的实现是:

# 转换为标题大小写的函数 
def generateTitleCase(input_string): 
      
    # 文章清单 
    articles = ["a", "an", "the"] 
      
    # 协调连接蛋白清单 
    conjunctions = ["and", "but", 
                    "for", "nor", 
                    "or", "so", 
                    "yet"] 
      
    # 一些短文清单 
    prepositions = ["in", "to", "for",  
                    "with", "on", "at", 
                    "from", "by", "about", 
                    "as", "into", "like", 
                    "through", "after", "over", 
                    "between", "out", "against",  
                    "during", "without", "before", 
                    "under", "around", "among", 
                    "of"] 
      
    # 合并3个列表 
    lower_case = articles + conjunctions + prepositions 
      
    # 输出文本的变量声明  
    output_string = "" 
      
    # 分隔字符串中的每个单词 
    input_list = input_string.split(" ") 
      
    # 检查每个词
    for word in input_list: 
          
        # 如果列表中存在该单词,则无需大写 
        if word in lower_case: 
            output_string += word + " "
              
        # 如果列表中不存在该单词,则将其大写 
        else: 
            temp = word.title() 
            output_string += temp + " "
              
      
    return output_string 
  
# 驱动程式码   
if __name__=='__main__':   
    input_text1 = "The quick brown fox jumps over the lazy dog."
    input_text2 = "A tale of two cities"
      
    print(generateTitleCase(input_text1))  
    print(generateTitleCase(input_text2))  

输出:

The Quick Brown Fox Jumps over the Lazy Dog. 
A Tale of Two Cities