词频统计。已知一段英文短文如下,编写程序,实现以下功能: (1)对短文中每个单词出现的次数进行统计,输出出现次数排在前十名的单词。 sentence='We can never get it by working for it directly.It comes,\ like happiness,to those who are aiming at something higher. It is\ a byproduct of great,simple living. The joy of living comes from\ what we put into living, not from what we seek to get from it.' 【提示】
时间: 2024-02-27 15:57:21 浏览: 26
可以先将短文中的标点符号去掉,然后将每个单词分离出来,最后使用Python中的Counter类进行统计。代码如下:
```python
from collections import Counter
import re
sentence = 'We can never get it by working for it directly.It comes,\ like happiness,to those who are aiming at something higher. It is\ a byproduct of great,simple living. The joy of living comes from\ what we put into living, not from what we seek to get from it.'
# 去掉标点符号
sentence = re.sub(r'[^\w\s]', '', sentence)
# 将每个单词分离出来
word_list = sentence.split()
# 统计单词出现次数
word_count = Counter(word_list)
# 输出出现次数排在前十名的单词
for k, v in word_count.most_common(10):
print(k, v)
```
输出结果为:
```
it 3
from 2
living 2
we 1
can 1
never 1
get 1
by 1
working 1
for 1
```