python - 如何预处理推文的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 文件?
解决方案
推荐阅读
- javascript - react-native-safe-area-context 是否适用于 Android 8 及更低版本?
- python - 编码器-解码器模型 AttributeError:“NoneType”对象没有属性“_inbound_nodes”
- c - 从位图和透明度颜色创建蒙版 - Windows GDI
- java - Hazelcast log4j 配置产生“java.lang.NoClassDefFoundError: org/apache/log4j/Logger”错误
- azure-functions - 将 Azure 函数请求记录为失败并返回状态 200
- javascript - 如何获取 jquery nice select 的值
- php - 侧边栏菜单下拉淹没 wordpress 不工作
- wpf - WPF中有没有办法将资源使用限制为StaticResource?
- php - 从推文中提取图片
- javascript - 检测文本区域和输入中的链接