我正在使用 Tweepy 收集关注者的数据。我可以打印返回的数据,但无论我如何尝试,都无法将数据以可重用的形式保存到文件中。
下面是我成功导出到 txt 文件的方法,但是当我将该文件调用到变量中时,它会设置一个字符数组,并且不会将其视为可用的数组。
这是 Tweepy 调用:
import sys
import tweepy
import json
# Key info removed
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.followers, screen_name="handle").pages():
ids.extend(page)
print ids
with open("followers.txt", 'w') as f:
f.write(str(ids))
我从中得到的是一个文件,其开头为:
[User(follow_request_sent=False...
如果我用
调用数据data = f.read()
print data[0] # returns '['
最佳答案
每个页面
都是tweepy User
对象的列表
。因此,当您执行以下操作时,您将丢失 tweepy 数据结构: ids.extend(page)
。
尝试下面的这段代码:
with open("followers.txt", 'a') as f: #open file first
for page in tweepy.Cursor(api.followers, screen_name='handle').pages():
for user_obj in page: #iterate through each User object
json.dump(user_obj._json, f) #dump each to file, f
f.write("\n") #you'll need this for Martjin's answer below to work.
感谢 Martjin Pieter 对 this question 的回答。您可以加载并离散访问您的数据。我修改他的代码片段的方式是将 jfile
附加到名为 user_jsons
的列表(这相当于您的 data
变量)。
user_jsons = []
with open("followers.txt", 'rb') as f:
for line in f:
while True:
try:
jfile = json.loads(line)
break
except ValueError:
# Not yet a complete JSON value
line += next(f)
user_jsons.append(jfile)
现在你有一个 json 对象列表...[7] 被截断
In [7]: user_jsons[0]
Out[7]: {u'blocked_by': False,
u'blocking': False,
u'contributors_enabled': False,
u'created_at': u'Thu Jan 30 18:33:13 +0000 2014',
...
In [8]: user_jsons[0]['screen_name']
Out[8]: u'some_users_handle'
您可能会找到 ipython 笔记本 here非常有用的资源,尤其是第 9 章。
关于python - 在 Tweepy 中以可用形式 (JSON) 提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35243036/