Python实现fix_capitalization句首大写函数时标点兼容问题如何解决?
代码问题分析与修正方案
原有实现的核心问题
- 分割逻辑缺陷:仅以
.作为句子分割依据,无法适配感叹号!、问号?等其他句末标点 - 标点丢失问题:按句号分割时会直接丢弃原字符串中的句末标点,后续硬拼接
.的操作会和原有的感叹号等标点冲突,也会改变原文本的空格格式 - 计数逻辑错误:不管句子开头原本是不是大写,直接每分割一段计数+1,不符合题目要求的「统计被大写的字母总数量」的要求
修正方案
实现思路
按照题目给出的提示,改用逐字符遍历的方式处理,完整保留原文本所有标点和空格格式:
- 初始化
capitalCount计数为0,空的结果字符串,以及next_is_start标记(标记下一个非空格字符是否为句子开头,初始值为True,因为文本首字符就是第一个句子的开头) - 遍历输入字符串的每个字符:
- 如果
next_is_start为True且当前字符是小写字母:将字符转为大写后拼接,计数+1,同时把next_is_start设为False - 如果当前字符是句末标点(
.,!,?):直接拼接字符,同时把next_is_start设为True - 其他情况(空格、大写字母、普通符号等):直接拼接字符即可,空格不会修改
next_is_start的状态,确保句子结束后的空格不影响下一句开头的识别
- 如果
修正后代码
def fix_capitalization(userString): capitalCount = 0 editedString = "" next_is_start = True # 标记下一个非空格字符是否是句子开头 for char in userString: if next_is_start: # 跳过空格,直到找到第一个字母 if char.isspace(): editedString += char elif char.islower(): # 小写转大写,计数+1 editedString += char.upper() capitalCount += 1 next_is_start = False else: # 本身就是大写或者其他符号,直接拼接 editedString += char next_is_start = False else: editedString += char # 遇到句末标点,标记下一个开头需要大写 if char in ('.', '!', '?'): next_is_start = True return capitalCount, editedString # print_menu函数调用示例 def print_menu(input_str): count, edited = fix_capitalization(input_str) print(f"大写的字母数量:{count}") print(f"编辑后的文本:{edited}")
测试效果
用示例文本测试:
test_str = "we'll continue our quest in space. there will be more shuttle flights and more shuttle crews and, yes; more volunteers, more civilians, more teachers in space. nothing ends here; our hopes and our journeys continue!" print_menu(test_str)
输出结果和要求的示例完全一致:
大写的字母数量:3
编辑后的文本:We'll continue our quest in space. There will be more shuttle flights and more shuttle crews and, yes; more volunteers, more civilians, more teachers in space. Nothing ends here; our hopes and our journeys continue!
内容的提问来源于stack exchange,提问作者helpthisnewbie540
相关产品推荐
相关产品推荐

