基于python将csv文件词频统计并将结果存入txt文件中
时间: 2024-03-27 19:40:48 浏览: 58
基于Python实现分析文本数据的词频
好的,我可以为您提供一个简单的Python代码来实现这个任务。您可以按照以下步骤进行操作:
1. 导入所需模块
```python
import csv
from collections import Counter
```
2. 读取CSV文件并获取数据
```python
with open('example.csv', 'r') as file:
reader = csv.reader(file)
data = [row for row in reader]
```
3. 将数据转换成单个字符串并进行词频统计
```python
text = ' '.join([str(elem) for elem in data])
word_counts = Counter(text.split())
```
4. 将结果写入TXT文件
```python
with open('word_counts.txt', 'w') as file:
for word, count in word_counts.most_common():
file.write(f"{word}: {count}\n")
```
完整代码如下:
```python
import csv
from collections import Counter
with open('example.csv', 'r') as file:
reader = csv.reader(file)
data = [row for row in reader]
text = ' '.join([str(elem) for elem in data])
word_counts = Counter(text.split())
with open('word_counts.txt', 'w') as file:
for word, count in word_counts.most_common():
file.write(f"{word}: {count}\n")
```
请注意替换文件名以匹配您自己的CSV文件名。
阅读全文