【发布时间】:2015-02-04 23:11:56
【问题描述】:
我第一次使用 Tweepy,我是 Python 新手。 我在 OAuth 之后使用以下代码使用 Tweepy 收集推文:
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
file = open('SOTU1.txt', 'a')
class CustomStreamListener(tweepy.StreamListener):
def on_status(self, status):
print status.text
def on_data(self, data):
json_data = json.loads(data)
file.write(str(json_data))
def on_error(self, status_code):
print >> sys.stderr, 'Encountered error with status code:', status_code
return True # Don't kill the stream
def on_timeout(self):
print >> sys.stderr, 'Timeout...'
return True # Don't kill the stream
生成的文本文件如下所示,并继续作为一个字符串对象:
{u'contributors': None, u'truncated': False, u'text': u'Lost my cool today
\U0001f602\U0001f63e like completely', u'in_reply_to_status_id': None, u'id':
557709279751581696, u'favorite_count': 0, u'source': u'<a
href="http://twitter.com/download/android" rel="nofollow">Twitter for
Android</a>', u'retweeted': False, u'coordinates': {u'type': u'Point',
u'coordinates': [-97.925459, 29.877993]}, u'timestamp_ms': u'1421803228687',
u'entities': {u'user_mentions': [], u'symbols': [], u'trends': [],
u'hashtags': [], u'urls': []}, u'in_reply_to_screen_name': None, u'id_str':
u'557709279751581696', u'retweet_count': 0, u'in_reply_to_user_id': None,
u'favorited': False, u'user': {u'follow_request_sent': None,
u'profile_use_background_image': True, u'default_profile_image': False, u'id':
1239731318, u'verified': False, u'profile_image_url_https':
我尝试了网站上提供的各种解决方案,但都没有奏效,因为它不是一个列表,而是一个字符串。我试图通过删除“u”将其变成字典形式,但是该对的右侧有没有被“”包围的单词。
我的目标是从每条推文中提取文本和地理编码,我希望使用 jq 在 bash 中处理 JSON 文件。但到目前为止,我无法将这些数据提供给 jq,而且很难确定哪一批行来自一条推文。
提前致谢!
【问题讨论】:
-
json_data = json.loads(data)- json_data 是一个字典,只有在您执行file.write(str(json_data))时才会再次变为字符串。如果您这样做只是为了探索获得的数据,请尝试使用pprint模块,该模块将为您提供更易读的文本。
标签: python json bash twitter dictionary