题目 编写一个程序来计算输入的英文句子中单词的频率。 按字母顺序对键进行排序后输出。不统计各种标点符号:!@#$%^&*,;:'?{[]/}. 输入样例:God is impartial , the people who has destiny in hand stands forever in thebalance both ends , the people who is grasped by destiny knows that God best ows destiny on him only. 输出 应该是:每行输出一个词 及其出现次数,用冒号分隔 God:2 best:1 both:1 by:1 destiny:3 ends:1 forever:1 grasped:1 hand:1 has:1 him:1 impartial:1 in:2 is:2 knows:1 on:1 only.:1 ows:1 people:2 stands:1 that:1 the:2 thebalance:1 who:2
时间: 2023-12-19 10:04:58 浏览: 131
好的,以下是 Python3 的实现代码:
```python
import re
sentence = input() # 输入英文句子
word_dict = {}
# 将句子中的标点符号去除,只保留单词
sentence = re.sub(r'[^\w\s]', '', sentence)
# 按空格分割单词,并统计每个单词出现的次数
for word in sentence.split():
if word.lower() in word_dict:
word_dict[word.lower()] += 1
else:
word_dict[word.lower()] = 1
# 按字母顺序对键进行排序
sorted_keys = sorted(word_dict.keys())
# 输出每个单词及其出现次数
for key in sorted_keys:
print(key + ':' + str(word_dict[key]))
```
输入样例:
```
God is impartial , the people who has destiny in hand stands forever in thebalance both ends , the people who is grasped by destiny knows that God best ows destiny on him only.
```
输出结果:
```
best:1
both:1
by:1
destiny:3
ends:1
forever:1
god:2
grasped:1
hand:1
has:1
him:1
impartial:1
in:2
is:2
knows:1
on:1
only:1
ows:1
people:2
stands:1
that:1
the:2
thebalance:1
who:2
```
阅读全文