python|英文标题格式化

Posted on 2020-04-16 15:52  可乐很难瘦  阅读(776)  评论(0编辑  收藏  举报

2020-04-16

正确的英文标题格式

  •  首字母大写
  • 英文的介词等需要全部小写
  • 位于开头的单词,必须首字母大写;无论是否是介词等

python处理字符串的函数

capitalize()

# 利用 capitalize()函数,将字符串的首字母转化为大写,其余为小写
L1 = ['AdmIn','anny','LUCY','sandY','wILl']
def normallize(name):
    return name.capitalize()
L2 = list(map(normallize,L1))
print(L2)

upper()

lower()

#将字符串全部转化为大写or小写
title = 'benny'
print(title.upper())
# 错误写法, 这两个方法是字符串的属性,不是单独的函数
# print(upper(title)) title = 'BENNY' print(title.lower())

title()

title = 'REVIEWS IN INORGANIC CHEMISTRY'
print(title.title())

# 不区分介词等,一律变成首字母大写
# Reviews In Inorganic Chemistry

ps:title()方法处理包含多个单词的字符串,可以将每个独立的单词首字母大写;capitalize()处理包含多个单词的字符串,只会将整个字符串的首个单词的首字母变为大写

最后的处理方法

import re
# 添加不需要首字母大写的对象;自定义
stop_words = ['ON', 'IN', 'AND', 'OF', 'A', 'AN', 'BETWEEN']
def isJudged(title): # 判断是否存在小写字母;本人遇到的情况只需要修正全部大写的字符串 res = re.search('[a-z]', title) # print(res) if res: return True return False # 核心功能,将首字母改为大写 def normallize(title): print('=======deal======') list = title.split(' ') new_list = [] for index, item in enumerate(list): if index == 0:
       # 首个字符串,一定首字母大写 new_list.append(item.capitalize())
else:
       # 停用词直接处理为小写
if item.upper() in stop_words: new_list.append(item.lower()) else: new_list.append(item.capitalize()) res = ' '.join(new_list) return res