python - Twitter 对字符串的情感分析

标签 python machine-learning scikit-learn nlp sentiment-analysis

我编写了一个程序,它获取包含推文和标签的 Twitter 数据(0 表示中性情绪,1 表示负面情绪)并预测推文的类别属于。 该程序在训练和测试集上运行良好。但是,我在使用字符串应用预测函数时遇到问题。我不知道该怎么做。

我尝试按照调用预测函数之前清理数据集的方式清理字符串,但返回的值形状错误。

import numpy as np
import pandas as pd
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
ps = PorterStemmer()
import re

#Loading dataset
dataset = pd.read_csv('tweet.csv')

#List to hold cleaned tweets
clean_tweet = []

#Cleaning tweets
for i in range(len(dataset)):
    tweet = re.sub('[^a-zA-Z]', ' ', dataset['tweet'][i])
    tweet = re.sub('@[\w]*',' ',dataset['tweet'][i])
    tweet = tweet.lower()
    tweet = tweet.split()
    tweet = [ps.stem(token) for token in tweet if not token in set(stopwords.words('english'))]
    tweet = ' '.join(tweet)
    clean_tweet.append(tweet)

from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features = 3000)
X = cv.fit_transform(clean_tweet)
X =  X.toarray()
y = dataset.iloc[:, 1].values

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y)

from sklearn.naive_bayes import GaussianNB
n_b = GaussianNB()
n_b.fit(X_train, y_train)
y_pred  = n_b.predict(X_test) 

some_tweet = "this is a mean tweet"  # How to apply predict function to this string

最佳答案

在新字符串上使用 cv.transform([cleaned_new_tweet]) 将新推文转换为现有文档术语矩阵。这将以正确的形状返回推文。

关于python - Twitter 对字符串的情感分析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56872294/

相关文章:

python - 用 Pandas 导入数据时卡住了错误

python - 寻找最相似的句子匹配

python - Tkinter Canvas 存储的项目被清除和召回

python - 使用 python 解释器安装 pip

machine-learning - 在实践中如何使用 TfidfVectorizer 加元数据进行分类?

machine-learning - MXNet 中自定义 eval_metric 的使用可能不正确

python - 如何解决 Sklearn KNN 未安装错误

python - 交叉验证 : cross_val_score function from scikit-learn arguments

python - 如何知道Python中模块的导入者是什么?

python - Tweepy 和 flask : failed to get request token