首页 > 解决方案 > 如何预处理推文的csv文件?

问题描述

我有一个 10K 推文的 csv 文件,其中包含所有信息,例如 id、位置、推文文本……对于情绪分析,首先我应该预处理这些推文,我使用以下代码,我的机器是带有 Python 3.6 的 IMAC:

import csv
import re
import numpy as np
from nltk.tokenize import word_tokenize
from string import punctuation
from string import punctuation 
from nltk.corpus import stopwords
class PreProcessTweets:
    def __init__(self):
        self._stopwords = set(stopwords.words('english') + list(punctuation) + ['AT_USER','URL'])

    def processTweets(self, list_of_tweets):
        processedTweets=[]
        for tweet in list_of_tweets:
            processedTweets.append((self._processTweet(tweet["text"]),tweet["label"]))
        return processedTweets

    def _processTweet(self, tweet):
        tweet = tweet.lower() # convert text to lower-case
        tweet = re.sub('((www\.[^\s]+)|(https?://[^\s]+))', 'URL', tweet) # remove URLs
        tweet = re.sub('@[^\s]+', 'AT_USER', tweet) # remove usernames
        tweet = re.sub(r'#([^\s]+)', r'\1', tweet) # remove the # in #hashtag
        tweet = word_tokenize(tweet) # remove repeated characters (helloooooooo into hello)
        return [word for word in tweet if word not in self._stopwords]
testDataSet= open("Twitter_data.csv")
tweetProcessor = PreProcessTweets()

preprocessedTestSet = tweetProcessor.processTweets(testDataSet)

但我收到以下错误:

TypeError: string indices must be integers

如何修复此代码以正确预处理我的 csv 文件?

标签: pythonmachine-learningtwitternlpsentiment-analysis

解决方案


推荐阅读