帮我写一个python代码,要可以分析得出excel文档中每一条中文评论的情感值,输出结果为对应的excel文档
时间: 2024-03-07 21:48:23 浏览: 22
好的,可以使用Python的pandas和TextBlob库来实现情感分析。以下是一个简单的示例代码:
```python
import pandas as pd
from textblob import TextBlob
# 读取Excel文件
df = pd.read_excel('input.xlsx')
# 定义函数获取情感值
def get_sentiment(text):
blob = TextBlob(str(text))
sentiment = blob.sentiment.polarity
if sentiment > 0:
return 'Positive'
elif sentiment < 0:
return 'Negative'
else:
return 'Neutral'
# 创建新列并应用函数
df['sentiment'] = df['评论'].apply(get_sentiment)
# 输出结果到Excel文件
df.to_excel('output.xlsx', index=False)
```
在这个示例代码中,我们首先使用pandas读取Excel文件,然后定义了一个名为`get_sentiment`的函数来获取每条评论的情感值。我们使用TextBlob库来计算情感值,如果情感值大于0则为正面评论,小于0则为负面评论,否则为中性评论。然后我们使用pandas的`apply`函数将`get_sentiment`函数应用到每一行评论上,并将结果保存到一个名为`sentiment`的新列中。最后,我们将结果输出到一个新的Excel文件中。
请确保在使用之前将代码中的文件名替换为您自己的Excel文件名。