【问题标题】:Parse JSON to CSV Twitter Data KeyError: 'user'将 JSON 解析为 CSV Twitter 数据 KeyError: 'user'
【发布时间】:2014-08-18 01:28:39
【问题描述】:

我正在尝试解析我现在在 JSON 文件中收集的一些推文数据。问题是一些推文中没有“用户”或“地点”。结果,我收到如下消息:

  File "<stdin>", line 18, in <module>
  KeyError: 'user'

所以我尝试添加一个 if-else 语句,但它仍然给我错误消息。你下一步怎么做?

for line in lines:
    try:
            tweet = json.loads(line)

            # Ignore retweets!
            if tweet.has_key("retweeted_status") or not tweet.has_key("text"):
                    continue

            # Fetch text from tweet
            text = tweet["text"].lower()

            # Ignore 'manual' retweets, i.e. messages starting with RT             
            if text.find("rt ") > -1:
                    continue

            tweets_text.append( text )
            # I added an if-else statement, but it's still having be the error message
            if tweet['user']:
                    tweets_location.append( tweet['user']['location'] )
            else:
                    tweets_location.append("")

    except ValueError:
            pass

【问题讨论】:

    标签: python json csv twitter


    【解决方案1】:

    使用dict.get

            if tweet.get('user'):
                    tweets_location.append(tweet['user'].get('location', ''))
            else:
                    tweets_location.append("")
    

    Why dict.get(key) instead of dict[key]?

    【讨论】:

      【解决方案2】:

      你得到一个 KeyError。如果要检查键是否在字典中,请执行以下操作:

      if 'user' in tweet:
          tweets_location.append( tweet['user']['location'] )
      

      或者你可以将它嵌入到 try..except 中:

      try:
          tweets_location.append( tweet['user']['location'] )
      except KeyError:
          tweets_location.append('')
      

      或者,您可以使用 dict 的 get 方法,如 XrXrXr 所建议的那样。 get 方法为您提供了一种提供默认值的便捷方式,即,您可以在一行中完成所有操作:

      tweets_location.append( tweet.get('user', '').get('location', '') )
      

      如果 'user' 不是 tweet 中的键,则默认为空字符串,如果 'location' 不是 tweet['user'] 的键,则默认为空字符串

      【讨论】:

        【解决方案3】:

        通过在 if 语句中执行 tweet['user'],您假设密钥 user 存在,这会引发 KeyError。您可以通过执行if 'user' in tweet 来测试密钥是否在字典中。或者,您可以处理KeyError,类似于处理ValueError

        try:
            ....
            try:
                tweets_location.append( tweet['user']['location'] )
            except KeyError:
                tweets_location.append("")
        except ValueError:
                pass
        

        【讨论】:

          猜你喜欢
          • 2017-07-31
          • 1970-01-01
          • 1970-01-01
          • 2022-12-13
          • 2023-03-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多