【问题标题】:KeyError when cleaning tweets column using stop words in python使用python中的停用词清理推文列时出现KeyError
【发布时间】:2020-11-16 01:29:22
【问题描述】:

我有一个推文数据框,我正在尝试清理我的“推文”列 - 删除停用词并使用词形还原。

下面是我的代码:

stop_words = set(stopwords.words('english'))
lemmatizer= WordNetLemmatizer()

sentence = df['tweet'].apply(nltk.sent_tokenize)

 0 [ 'country year happy']
 1 [ 'wish happy year']
 2 [ 'live year together']

for i in range(len(sentence)): 
    words=nltk.word_tokenize(str(sentence[i]))
    words=[lemmatizer.lemmatize(word) for word in words if word not in 
          set(stopwords.words('english'))]
    sentence[i]=' '.join(words)

上面的代码给了我以下错误:(我包含了所有的回溯)

 KeyError  Traceback (most recent call last)
<ipython-input-384-f4bb836363e1> in <module>
  1 for i in range(len(sentence)):
----> 2     words=nltk.word_tokenize(str(sentence[i]))
  3     words=[lemmatizer.lemmatize(word) for word in words if word not in 
      set(stopwords.words('english'))]
  4     sentence[i]=' '.join(words)

~\anaconda3\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
   869         key = com.apply_if_callable(key, self)
   870         try:
   --> 871     result = self.index.get_value(self, key)
   872 
   873             if not is_scalar(result):

~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_value(self, 
  series, key)
  4403         k = self._convert_scalar_indexer(k, kind="getitem")
  4404         try:
  -> 4405             return self._engine.get_value(s, k, 
  tz=getattr(series.dtype, "tz", None))
  4406         except KeyError as e1:
  4407             if len(self) > 0 and (self.holds_integer() or 
  self.is_boolean()):

  pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

  pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

  pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

  pandas\_libs\hashtable_class_helper.pxi in 
  pandas._libs.hashtable.Int64HashTable.get_item()

  pandas\_libs\hashtable_class_helper.pxi in 
  pandas._libs.hashtable.Int64HashTable.get_item()

  KeyError: 34

我该如何解决这个错误?

另外,我怎样才能在我的数据框中获得结果 - 添加另一列与结果?

【问题讨论】:

    标签: python nlp nltk tokenize stop-words


    【解决方案1】:

    使用sentence.iloc[i] 而不是sentence[i]

    说明

    KeyError 表示df.index 中没有34

    sentence是熊猫系列;当您访问sentence[i] 时,Pandas 将首先尝试使用基于索引的索引 (df.loc),但如果您的索引是非数字的,则会回退到基于位置的索引 (df.iloc)。因此,如果您的索引恰好是非数字的,则此代码可能会起作用,但否则它不会按照您的预期进行。您可以通过显式使用基于位置的索引 (df.iloc) 来修复此错误。

    举个独立的例子:

    不起作用

    import pandas as pd
    df = pd.DataFrame({'index': [10,20], 'tweets': [['hello world'],['foo bar']]}).set_index('index')
    sentence = df['tweets']
    
    for i in range(len(sentence)):
        print(sentence[i])
    

    作品

    import pandas as pd
    df = pd.DataFrame({'index': [10,20], 'tweets': [['hello world'],['foo bar']]}).set_index('index')
    sentence = df['tweets']
    
    for i in range(len(sentence)):
        print(sentence.iloc[i])
    

    提示:与手动遍历 Dataframe 中的行相比,将逻辑编写为函数并使用 df.apply 通常更安全、更高效。

    【讨论】:

    • 错误已解决,但似乎我写的循环没有做我想要的。句子栏中还有停用词。
    • 我认为问题出在这部分:words = [lemmatizer.lemmatize(word) for word in words if word not in stop_words]。未词形化的词可能不是停用词,但在词形化后变成了停用词。尝试添加另一个words = [word for word in words if word not in stop_words] 步骤。
    • 哦,还有另一个问题:如果您检查nltk.word_tokenize(str(sentence.iloc[i])),它可能也没有按照您的意愿进行操作,因为您将['hello world'] 转换为['[', "'hello", 'world', "'", ']'],这意味着您有额外的引号和括号。你的tweet 列表中有什么?如果只有一行你可以做nltk.word_tokenize(sentence.iloc[0][0]),否则你需要正确地遍历列表而不是把它们变成字符串。
    • 谢谢,我添加了 'words' 的更正(您的第一条评论)并修复了 'word_tokenize' 问题。它仍然没有解决问题。列中有停用词和未引理的词。您对此还有其他建议吗?
    • 技术上这是一个单独的问题;您能否(1)将您的新代码添加到您的问题中并(2)显示一些显示问题的示例输入/输出?
    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-18
    • 2013-05-05
    • 1970-01-01
    相关资源
    最近更新 更多