TypeError:字符串索引必须是整数-清理我的文本

问题描述 投票:0回答:1

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

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:字符串索引必须为整数

怎么了?我该如何解决?

python function twitter
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.