基于知网情感词典的对excel里面的中文文本进行情感分析代码
时间: 2023-09-01 18:11:02 浏览: 58
以下是基于知网情感词典的对Excel里面的中文文本进行情感分析的代码:
```python
import pandas as pd
import jieba
# 读取Excel文件
df = pd.read_excel('example.xlsx')
# 加载情感词典
posdict = []
negdict = []
with open('pos.txt', 'r', encoding='utf-8') as f:
for line in f:
posdict.append(line.strip())
with open('neg.txt', 'r', encoding='utf-8') as f:
for line in f:
negdict.append(line.strip())
# 对每一行文本进行情感分析
results = []
for index, row in df.iterrows():
text = str(row['text'])
seg_list = jieba.cut(text)
pos_count = 0
neg_count = 0
for word in seg_list:
if word in posdict:
pos_count += 1
elif word in negdict:
neg_count += 1
if pos_count > neg_count:
sentiment = 'Positive'
elif pos_count < neg_count:
sentiment = 'Negative'
else:
sentiment = 'Neutral'
results.append(sentiment)
# 将分析结果保存到Excel中
df['sentiment'] = results
df.to_excel('example_with_sentiment.xlsx', index=False)
```
其中,`example.xlsx`是待分析的Excel文件,包含了一个名为`text`的列,存储了中文文本。`pos.txt`和`neg.txt`是情感词典文件,分别存储了积极情感词和消极情感词。代码会依次读取每一行文本,使用`jieba`库对其进行分词,然后统计其中的积极情感词和消极情感词的个数,最终根据哪类情感词更多来判断该文本的情感倾向,并将结果保存到名为`example_with_sentiment.xlsx`的新Excel文件中。注意,代码中只使用了情感词典,没有考虑否定词等情感修饰词,因此结果可能不够准确。