用pandas统计不同单词数
时间: 2023-06-29 14:11:05 浏览: 137
可以使用Python中的pandas库来统计不同单词的数量,具体步骤如下:
1. 读取文本文件并将其转换为一个字符串。
例如,我们有一个名为“example.txt”的文件,它包含以下内容:
```
Hello world
This is an example file
Containing some random text
With some words appearing more than once
```
可以通过以下代码读取文本文件并将其转换为一个字符串:
```python
import pandas as pd
with open('example.txt', 'r') as file:
text = file.read().replace('\n', ' ')
```
2. 将字符串分割成单词列表。
可以使用Python中的split()方法将字符串分割成单词列表:
```python
word_list = text.split()
```
3. 使用pandas创建一个DataFrame来计算每个单词出现的次数。
```python
df = pd.DataFrame(word_list, columns=['word'])
word_count = df['word'].value_counts()
```
`word_count`是一个pandas Series,其中包含每个单词出现的次数。可以通过以下方式打印出所有单词及其出现次数:
```python
print(word_count)
```
输出结果如下:
```
some 2
With 1
is 1
an 1
example 1
appearing 1
more 1
text 1
Containing 1
file 1
than 1
random 1
words 1
Hello 1
world 1
Name: word, dtype: int64
```
这表示单词“some”出现了2次,“With”、“is”、“an”等单词仅出现了1次。
阅读全文
相关推荐
![](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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)