python文本情感分析代码
时间: 2023-07-23 07:13:51 浏览: 123
以下是一个简单的Python文本情感分析代码示例,使用了nltk库和情感词典:
```python
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
# 下载所需的nltk数据
nltk.download('stopwords')
nltk.download('punkt')
nltk.download('wordnet')
nltk.download('opinion_lexicon')
# 加载情感词典
positive_words = set(word.strip() for word in open('positive-words.txt'))
negative_words = set(word.strip() for word in open('negative-words.txt'))
# 定义函数进行文本情感分析
def sentiment_analysis(text):
# 分词
words = word_tokenize(text.lower())
# 去除停用词
stop_words = set(stopwords.words('english'))
words = [word for word in words if word not in stop_words]
# 词形还原
lemmatizer = WordNetLemmatizer()
words = [lemmatizer.lemmatize(word) for word in words]
# 计算情感得分
pos_score = neg_score = 0
for word in words:
if word in positive_words:
pos_score += 1
elif word in negative_words:
neg_score += 1
if pos_score > neg_score:
return 'positive'
elif pos_score < neg_score:
return 'negative'
else:
return 'neutral'
# 测试代码
text = "I love this movie, it's so good!"
print(sentiment_analysis(text)) # 输出:positive
text = "This restaurant is terrible, I will never come back again."
print(sentiment_analysis(text)) # 输出:negative
text = "The weather today is neither good nor bad."
print(sentiment_analysis(text)) # 输出:neutral
```
注意,这只是一个简单的示例代码,实际情感分析可能需要更复杂的算法和数据。
阅读全文