从推文Python

时间:2017-05-31 23:25:45

标签: python loops nltk tweets stop-words

我正在尝试删除我从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

追溯的片段:

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

我之前的尝试是循环遍历数据框的列,推文。推文的第一列是&#34; id&#34;。

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')

1 个答案:

答案 0 :(得分:1)

您对列表索引感到困惑:

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

请注意tweets是字典; tweets['text']字符串列表。因此,for i in tweets返回tweets中的所有键:字典键以任意顺序。似乎&#34; id&#34;是第一个返回的人。当您尝试分配tweets['text-filtered']['id'] = filtered_sentence时,就没有这样的元素。

尝试更轻柔地编码:从内部开始,一次编码几行,然后逐步完成更复杂的控制结构。在继续之前调试每个添加。在这里,你似乎已经失去了对什么是数字索引,什么是列表以及什么是字典的感觉。

由于您还没有完成任何可见的调试或提供了上下文,我无法为您修复整个程序 - 但这应该可以让您入门。

相关问题