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

如何编写实现逐词输入生成规范句子并统计词数的Python程序?

完善你的Python句子处理程序

嘿,我来帮你搞定这个程序的完善工作!先指出你现有代码里的一个小问题:最后一行的return listMessage在普通脚本里会报错,因为return只能在函数内部使用,咱们先把这个问题修正,再一步步实现你要的两个功能。

完整的解决方案代码

listMessage = []
message = input('Enter first word of your message: ')
while message != 'done!':
    listMessage.append(message)
    message = input('Please enter the next word of your message or type done! when complete ')

# 处理并输出格式正确的完整句子
if listMessage:  # 先判断是否输入了有效单词,避免空列表报错
    # 方式1:首词首字母大写,其余字母转为小写(适合统一格式)
    capitalized_first_word = listMessage[0].capitalize()
    # 方式2:仅首字母大写,保留原词其余字母的大小写(比如输入'tHE'会变成'THE')
    # capitalized_first_word = listMessage[0][0].upper() + listMessage[0][1:]
    
    # 拼接成完整句子,词间用空格分隔,句末加句号
    full_sentence = ' '.join([capitalized_first_word] + listMessage[1:]) + '.'
    print(full_sentence)
    
    # 统计并输出单词数量
    word_count = len(listMessage)
    print(f"There are {word_count} words in the sentence.")
else:
    print("You didn't enter any words!")

代码功能说明

  • 移除无效的return语句:你的原代码不是函数,所以不需要return,直接处理收集到的单词列表即可。
  • 空输入判断:加了if listMessage的判断,防止用户直接输入done!导致空列表的情况,避免后续处理报错。
  • 首词大写处理:提供了两种方式,你可以根据需求选择:
    • capitalize():会把首字母大写,其余字母转为小写,适合需要统一句子格式的场景。
    • 手动拼接首字母大写+原词剩余部分:保留原单词的其他字母大小写,更灵活。
  • 句子拼接:用' '.join()方法高效拼接单词列表,比循环拼接字符串更简洁高效。
  • 单词数量统计:直接用len(listMessage)获取列表长度,就是单词的数量,简单准确。

示例运行效果

当你依次输入:the、cat、ran、home、quickly,最后输入done!,程序会输出:

The cat ran home quickly.
There are 5 words in the sentence.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:02:00