You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Tweepy采集Twitter数据时遇TypeError: unhashable type: 'slice'错误求助

Fixing "TypeError: unhashable type: 'slice'" in Tweepy Twitter Data Collection Script

我看到你在用Tweepy采集Twitter数据做情感分析时碰到了这个切片相关的错误,咱们来一步步拆解问题、解决它。

错误根源分析

这个TypeError本质是因为你处理API返回数据的方式不对:
当你使用tweepy.parsers.JSONParser()时,api.search()返回的是一个结构明确的字典,其中实际的推文列表存在'statuses'这个键下。但你现在用list(data.values())[0]或list(data.values())[1][1:]来提取数据,完全是在“猜”数据的位置——Python字典的键顺序(尤其是旧版本)是不确定的,很容易拿到非序列类型的对象,后续的切片操作[1:]自然就会抛出“不可哈希类型:切片”的错误。

修正步骤与完整代码

下面是修复后的完整脚本,我会标注关键的修改点:

import tweepy
import pandas as pd
import numpy as np
import time  # 补上你遗漏的time模块导入

# 替换成你的真实密钥
CONSUMER_KEY = "your_consumer_key"
CONSUMER_SECRET = "your_consumer_secret"
ACCESS_TOKEN = "your_access_token"
ACCESS_SECRET = "your_access_secret"

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
# 可选:加上wait_on_rate_limit=True,让Tweepy自动处理API频率限制
api = tweepy.API(auth, parser=tweepy.parsers.JSONParser(), wait_on_rate_limit=True)

# 搜索查询
searchquery = '"atiku" -filter:retweets'
# 第一次请求:直接通过'statuses'键获取推文列表
data = api.search(q=searchquery, count=100, lang='en', result_type='mixed')
data_all = data['statuses']

while len(data_all) <= 20000:
    time.sleep(5)
    # 取最后一条推文的ID,减1是为了避免重复获取同一条推文
    last_id = data_all[-1]['id'] - 1
    data = api.search(q=searchquery, count=100, lang='en', result_type='mixed', max_id=last_id)
    new_tweets = data['statuses']
    
    # 如果没有新推文了,直接跳出循环,避免无限等待
    if not new_tweets:
        print("No more tweets available to collect.")
        break
    
    data_all.extend(new_tweets)

print(f"Successfully collected {len(data_all)} tweets!")
# 转成DataFrame方便后续情感分析
tweet_df = pd.DataFrame(data_all)
print(tweet_df[['created_at', 'text', 'user']].head())

额外注意事项

  • API频率限制:如果加上wait_on_rate_limit=True,Tweepy会自动在达到Twitter的API调用上限时等待,不用手动设置time.sleep(),更省心。
  • 避免重复数据:使用max_id时必须减1,否则每次请求都会重复获取上一次的最后一条推文。
  • 终止条件:加入了if not new_tweets的判断,当没有更多推文可获取时会自动停止,防止无限循环。

内容的提问来源于stack exchange,提问作者0xsegfault

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:37:23