温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Twitter sentiment analysis on a string
machine-learning nlp python scikit-learn sentiment-analysis

python - Twitter情绪分析

发布于 2020-03-27 11:15:37

我编写了一个程序,该程序接收包含推文和标签的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

查看更多

查看更多

提问者
Imanpal Singh
被浏览
140
Toodle Pip 2019-07-03 22:50

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