【发布时间】:2017-06-01 23:35:48
【问题描述】:
我正在尝试从我从 Twitter 导入的推文中删除停用词。删除停用词后,字符串列表将放置在同一行的新列中。我可以轻松地一次完成这一行,但是当尝试在整个数据帧上循环该方法时似乎没有成功。
我该怎么做?
我的数据片段:
tweets['text'][0:5]
Out[21]:
0 Why #litecoin will go over 50 USD soon ? So ma...
1 get 20 free #bitcoin spins at...
2 Are you Bullish or Bearish on #BMW? Start #Tra...
3 Are you Bullish or Bearish on the S&P 500?...
4 TIL that there is a DAO ExtraBalance Refund. M...
以下工作在单行场景中:
from nltk.corpus import stopwords
stop_words = set(stopwords.words('english'))
tweets['text-filtered'] = ""
word_tokens = word_tokenize(tweets['text'][1])
filtered_sentence = [w for w in word_tokens if not w in stop_words]
tweets['text-filtered'][1] = filtered_sentence
tweets['text-filtered'][1]
Out[22]:
['get',
'20',
'free',
'#',
'bitcoin',
'spins',
'withdraw',
'free',
'#',
'btc',
'#',
'freespins',
'#',
'nodeposit',
'#',
'casino',
'#',
'...',
':']
我的循环尝试没有成功:
for i in tweets:
word_tokens = word_tokenize(tweets.get(tweets['text'][i], False))
filtered_sentence = [w for w in word_tokens if not w in stop_words]
tweets['text-filtered'][i] = filtered_sentence
回溯的sn-p:
Traceback (most recent call last):
File "<ipython-input-23-6d7dace7a2d0>", line 2, in <module>
word_tokens = word_tokenize(tweets.get(tweets['text'][i], False))
...
KeyError: 'id'
根据@Prune 的回复,我已经设法纠正了我的错误。这是一个潜在的解决方案:
count = 0
for i in tweets['text']:
word_tokens = word_tokenize(i)
filtered_sentence = [w for w in word_tokens if not w in stop_words]
tweets['text-filtered'][count] = filtered_sentence
count += 1
我之前的尝试是遍历数据框的列,推文。推文中的第一列是“id”。
tweets.columns
Out[30]:
Index(['id', 'user_bg_color', 'created', 'geo', 'user_created', 'text',
'polarity', 'user_followers', 'user_location', 'retweet_count',
'id_str', 'user_name', 'subjectivity', 'coordinates',
'user_description', 'text-filtered'],
dtype='object')
【问题讨论】:
-
当你得到一个解决方案时,请记得给有用的东西投票并接受你最喜欢的答案(即使你必须自己写),这样 Stack Overflow 才能正确存档问题。跨度>
标签: python loops nltk tweets stop-words