【问题标题】:Removing stopwords from tweets Python从推文 Python 中删除停用词
【发布时间】: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


【解决方案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 时,没有这样的元素。

尝试更温和地编写代码:从内部开始,一次编写几行代码,然后逐步进入更复杂的控制结构。在继续之前调试每个添加。在这里,您似乎对什么是数字索引、什么是列表以及什么是字典失去了意识。

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

【讨论】:

  • 我在索引、列表和字典之间的混淆是问题所在!我已根据您的建议更新了答案
猜你喜欢
  • 1970-01-01
  • 2020-11-02
  • 2013-12-16
  • 1970-01-01
  • 2013-12-17
  • 2018-02-25
  • 2021-03-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多