You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现文本句子首字母大写?Python代码输出异常求修正

解决句子首字母大写后丢失句号的问题

你的思路方向是对的,但问题出在分割后没有把句子间的分隔符(. )重新加回去。你用split('. ')把文本拆成了一个个去掉句号的句子,然后直接打印每个处理后的句子,自然就丢失了原来的句号和空格。

改进方案

我们可以先处理每个句子的首字母大写,再用. 把处理后的句子重新拼接起来,这样就能完整保留句子结构。另外,还要注意处理空句子的情况(比如连续出现两个句号的场景),以及避免用capitalize()方法(它会把句子其余字符都转成小写,不符合你只想首字母大写的需求)。

改进后的代码

text = input("Enter the text: \n")
# 按". "分割句子
sentences = text.split('. ')
processed_sentences = []

for sentence in sentences:
    if sentence:
        # 仅将句子第一个字符大写,其余字符保持原样
        processed = sentence[0].upper() + sentence[1:]
        processed_sentences.append(processed)
    else:
        # 处理空句子(比如连续两个句号的情况)
        processed_sentences.append(sentence)

# 用". "拼接所有处理后的句子
result = '. '.join(processed_sentences)
print(result)

测试你的示例输入

输入:

"we have good news and bad news about your emissaries to our world," the extraterrestrial ambassador informed the Prime Minister. the good news is they tasted like chicken."

输出:

"We have good news and bad news about your emissaries to our world," the extraterrestrial ambassador informed the Prime Minister. The good news is they tasted like chicken."

完美符合你的预期!

内容的提问来源于stack exchange,提问作者ajstc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:31:49