python查看一段文本中出现了哪些词 按词频降序排列
时间: 2023-06-01 10:01:45 浏览: 93
可以使用Python中的Counter和split函数来实现。
示例代码:
```python
from collections import Counter
text = "Python is a popular programming language. It was created in 1991 by Guido van Rossum."
# 将文本分割成单词列表
words = text.split()
# 统计单词出现频率
word_counts = Counter(words)
# 按照词频降序排列
sorted_word_counts = sorted(word_counts.items(), key=lambda x: x[1], reverse=True)
# 输出结果
for word, count in sorted_word_counts:
print(f"{word}: {count}")
```
输出结果:
```
in: 1
1991: 1
by: 1
created: 1
Guido: 1
Rossum.: 1
was: 1
Python: 1
is: 1
programming: 1
popular: 1
language.: 1
a: 1
```
注意,这里没有考虑大小写和标点符号的问题,如果需要更准确的结果,可以使用正则表达式或其他方法进行处理。
相关问题
python选择一个文本进行词频统计,实现输入一个词,统计出现次数
可以使用Python中的`collections`模块来进行词频统计。以下是一个简单的代码示例:
```python
from collections import Counter
# 读取文本内容
with open('file.txt', 'r') as f:
text = f.read()
# 转换成小写并分割成单词
words = text.lower().split()
# 统计词频
word_counts = Counter(words)
# 输入一个词,输出出现次数
input_word = input("请输入一个词:")
count = word_counts.get(input_word.lower(), 0)
print(f"{input_word}出现的次数为:{count}")
```
在这个示例中,我们首先使用`open()`函数读取文本文件(这里假定文件名为`file.txt`)中的内容。接着,我们使用`lower()`将文本内容转换成小写,并使用`split()`将文本分割成单词。
然后,我们使用`collections`模块中的`Counter`类来对单词做词频统计。最后,我们输入一个词,通过`get()`方法获取该词出现的次数,并输出结果。需要注意的是,我们在获取词频时将输入的词转换成小写,以保证大小写不敏感。如果词频统计中没有该词出现,那么输出的次数为0。
Python用jieba库进行文本词频统计::一篇文章,出现了哪些词?哪些词出现的最多?
好的,针对您的问题,可以使用Python中的jieba库进行文本词频统计,具体操作如下:
1. 安装jieba库:
```
pip install jieba
```
2. 导入jieba库并读取文本文件:
```python
import jieba
with open('text.txt', 'r', encoding='utf-8') as f:
text = f.read()
```
3. 使用jieba库对文本进行分词:
```python
words = jieba.cut(text)
```
4. 统计各词出现的频率:
```python
word_freq = {}
for word in words:
if word not in word_freq:
word_freq[word] = 1
else:
word_freq[word] += 1
```
5. 排序并输出结果:
```python
sorted_word_freq = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)
print('出现最多的前10个词:')
for word, freq in sorted_word_freq[:10]:
print(word, freq)
print('所有出现过的词:')
for word, freq in sorted_word_freq:
print(word, freq)
```
这样,就可以得到该文章中出现的所有词以及它们的出现频率,从而找到出现最多的前10个词。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)