python 接收元素为单词的列表,统计每个单词出现的次数,根据出现次数排序,输出出现频率最高的50个单词及其出现次数
时间: 2023-07-16 07:14:11 浏览: 49
可以使用 Python 的 Counter 模块来实现单词计数,并使用 sorted 函数来按照出现次数排序。以下是示例代码:
```python
from collections import Counter
# 假设单词列表为 words
word_count = Counter(words)
top_50 = word_count.most_common(50)
for word, count in top_50:
print(f"{word}: {count}")
```
解释:
1. 首先导入 Counter 模块。
2. 使用 Counter 函数对单词列表进行计数,得到一个字典,其中键为单词,值为出现次数。
3. 使用 most_common 函数获取出现次数最多的 50 个单词及其出现次数,返回一个列表,其中每个元素为一个元组,第一个元素为单词,第二个元素为出现次数。
4. 遍历列表,输出每个单词及其出现次数。
相关问题
Python统计每个单词出现的次数并降序输出
可以使用Python中的collections模块来实现单词计数功能,具体操作步骤如下:
1. 将文本内容读取并存储到一个字符串变量中;
2. 对字符串进行处理,去除标点符号、转换为小写等操作;
3. 使用split()方法将字符串分割成单词列表;
4. 使用collections模块中的Counter类进行单词计数,并将结果存储到一个字典中;
5. 对字典进行按值降序排序,并输出结果。
下面是代码示例:
```python
import string
from collections import Counter
# 读取文本内容
with open('text.txt', 'r') as f:
content = f.read()
# 处理字符串,去除标点符号、转换为小写
content = content.translate(str.maketrans('', '', string.punctuation)).lower()
# 分割字符串成单词列表
words = content.split()
# 使用Counter进行单词计数
word_count = Counter(words)
# 按值降序排序,并输出结果
for word, count in sorted(word_count.items(), key=lambda x: x[1], reverse=True):
print(word, count)
```
注意,这里的text.txt是你需要统计的文本文件名,可以根据实际情况进行修改。
python.统计英文句子中的单词出现的次数,输出次数最高的5个单词及次数。
好的,我可以为您提供帮助。您可以使用Python中的Counter模块来统计单词出现次数。下面是实现代码:
```python
from collections import Counter
# 将句子转换为小写并分割成单词
sentence = "This is a test sentence. This is another test sentence."
words = sentence.lower().split()
# 使用Counter模块统计单词出现次数
word_counts = Counter(words)
# 输出出现次数最高的5个单词及次数
top_five = word_counts.most_common(5)
print(top_five)
```
输出结果为:
```
[('is', 2), ('test', 2), ('this', 2), ('a', 1), ('sentence.', 1)]
```
上述代码中,我们首先将要统计的句子转换为小写并分割成单词。接着,使用Counter模块统计每个单词出现的次数。最后,使用most_common方法获取出现次数最高的5个单词及次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)