首页 > 解决方案 > TypeError:字符串索引必须是整数 - 清理我的文本

问题描述

尝试使用此功能清理推文:

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"])))
        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]

当我想使用它时:

preprocessedTestSet = tweetProcessor.processTweets(tweet)

我收到了这个输出

TypeError:字符串索引必须是整数

怎么了?我该如何解决?

标签: pythonfunctiontwitter

解决方案


假设tweet是一个字符串。你应该按原样通过它。您使用tweet["Text"]了 which 是对字符串的非法操作,因为索引必须是整数。

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

或者更多 Pythonic:

def processTweets(self, list_of_tweets):
    return [self._processTweet(tweet) for tweet in list_of_tweets]

笔记:

您可能忘记r""在某些正则表达式中使用原始字符串 ( )。


推荐阅读