使用python编写一个程序,接受用户输入的一行英文句子(假设该句子仅由英文单词及空格构成,不包括逗号等符号),统计并输出该行句子包含的单词个数及单词的平均长度
时间: 2024-03-23 21:35:58 浏览: 62
好的,您可以参考以下代码实现:
```python
sentence = input("请输入一行英文句子:")
words = sentence.split() # 按空格分割句子,得到单词列表
word_count = len(words) # 统计单词个数
total_len = sum(len(word) for word in words) # 计算所有单词长度之和
avg_len = total_len / word_count # 计算平均长度
print("单词个数为:", word_count)
print("平均长度为:", avg_len)
```
程序首先会提示用户输入一行英文句子,然后使用 `split()` 方法将句子按空格分割成单词列表。接着,程序使用 `len()` 函数统计单词个数,使用列表推导式和 `sum()` 函数计算单词长度之和,再除以单词个数算出平均长度。最后,程序输出单词个数和平均长度。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)