2017-05-31 8 views
0

Twitterからインポートしたツイートからストップワードを削除しようとしています。ストップワードを削除すると、文字列のリストは同じ行の新しい列に配置されます。私は簡単に一度にこの1行を達成することができますが、データフレーム全体でメソッドをループしようとすると成功しないようです。ツイートのストップワードを削除するPython

どうすればいいですか?

私のデータの抜粋:単一行のシナリオで

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' 

@プルーンの返信に基づいて、私は間違いを訂正することができました。ここには潜在的な解決策があります:

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

解決に至ったときは、有用なものを優先して投票し、好きな答えを受け入れることを覚えておいてください。そうすれば、Stack Overflowは質問を適切にアーカイブすることができます。 – Prune

答えて

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に返します。辞書キーは任意の順序で返します。 "id"が最初に返されたようです。 tweets['text-filtered']['id'] = filtered_sentenceを割り当てようとすると、そのような要素はありません。

内部を開始し、一度に数行をコードし、より複雑な制御構造に作業を進めてください。あなたが行く前にそれぞれの追加をデバッグしてください。ここでは、数値インデックスとは何か、リストとは何か、辞書は何ですか?

あなたは目に見えるデバッグを行っていないか、コンテキストを提供していないので、プログラム全体を修正することはできません。

+0

インデックス、リスト、辞書間の混乱が問題でした!提案した内容に基づいて回答を更新しました – Kevin

関連する問題