程序设计] 题目:键盘输入任意一句英文,输出其单词个数要求:每个单词之间以空格为分隔符例如: 【请输入英文语句:1To the world you may be one person, but to one person you may be the world.【英文单词个数为:]17 注意:部分源程序给出如下。请勿改动主函数main和其它函数中的 任何内容,仅在函数的注释标志之间填入所编写的若干语句。 def main( ): s=input("【请输入英文语句:1") n=0 #**********Program ********** #********** End ********** print("【英文单词个数为:]%d"%n) name - '__main__': main()
时间: 2025-05-24 21:01:53 浏览: 20
### Python 实现统计英文句子中单词数量
以下是基于 Python 编写的程序,用于统计输入的英文句子中的单词数量。该程序通过 `input()` 函数接收用户输入的句子,并利用字符串的 `split()` 方法将句子拆分为单独的单词,最后计算这些单词的数量。
```python
def count_words():
sentence = input("请输入一个英文句子: ")
words = sentence.split() # 使用 split() 将句子按照空白字符分割成单词列表[^1]
word_count = len(words) # 计算单词列表的长度即为单词总数[^2]
print(f"句子中共有 {word_count} 个单词。")
count_words()
```
#### 程序说明
- 用户可以通过控制台输入任意英文句子。
- 句子会被自动分解为多个单词,`split()` 默认会根据空格或其他空白符(如制表符 `\t` 或换行符 `\n`)进行分隔[^3]。
- 利用内置函数 `len()` 来获取单词列表的总长度,从而得到句子中的单词数目。
### 进一步优化
为了提高准确性,可以进一步处理特殊字符或大小写问题:
```python
import string
def count_words_cleaned():
sentence = input("请输入一个英文句子: ").lower() # 转换为小写字母以便统一处理
translator = str.maketrans('', '', string.punctuation) # 创建翻译器移除标点符号
cleaned_sentence = sentence.translate(translator) # 移除所有标点符号
words = cleaned_sentence.split() # 分割清洗后的句子
word_count = len(words)
print(f"清理后的句子共有 {word_count} 个单词。")
count_words_cleaned()
```
在此版本中:
- 所有的大写字母被转换为小写字母以消除因大小写不同而导致的错误统计。
- 使用 `string.punctuation` 和 `str.translate()` 去掉句子里的所有标点符号,防止它们干扰单词划分逻辑。
---
阅读全文
相关推荐



















