假设经过专业⼈⼠构建有: negtive.txt positive.txt 两个情感词典, 使用csv、jieba、os、re、pandas模块对csv文件进⾏统计, 输出结果 ⽂件名、正⾯词数、负⾯词数
时间: 2023-07-10 18:41:38 浏览: 76
好的,可以按照以下步骤进行操作:
1. 导入所需的模块
```python
import os
import re
import jieba
import pandas as pd
```
2. 定义函数读取情感词典
```python
def read_sentiment_dict(filename):
with open(filename, 'r', encoding='utf-8') as f:
words = [line.strip() for line in f]
return words
```
3. 分别读取正向情感词典和负向情感词典
```python
pos_dict = read_sentiment_dict('positive.txt')
neg_dict = read_sentiment_dict('negative.txt')
```
4. 定义函数对文本进行情感分析,返回正向情感词数和负向情感词数
```python
def analyze_sentiment(text, pos_dict, neg_dict):
pos_count = 0
neg_count = 0
words = jieba.lcut(text)
for word in words:
if word in pos_dict:
pos_count += 1
elif word in neg_dict:
neg_count += 1
return pos_count, neg_count
```
5. 定义函数统计csv文件中各行文本的情感词数
```python
def count_sentiment_words(csv_filename, pos_dict, neg_dict):
df = pd.read_csv(csv_filename)
results = []
for index, row in df.iterrows():
text = row['text']
pos_count, neg_count = analyze_sentiment(text, pos_dict, neg_dict)
results.append({
'filename': row['filename'],
'pos_count': pos_count,
'neg_count': neg_count
})
return pd.DataFrame(results)
```
6. 执行函数并保存结果到csv文件
```python
result_df = count_sentiment_words('input.csv', pos_dict, neg_dict)
result_df.to_csv('output.csv', index=False)
```
最终输出的结果文件output.csv中将包含每行文本所在的文件名、正向情感词数和负向情感词数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)