【问题标题】:Parse massive JSON string from Tweepy or convert to dict/JSON format从 Tweepy 解析大量 JSON 字符串或转换为 dict/JSON 格式
【发布时间】: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


【解决方案1】:
def on_data(self, data):
    json_data = json.loads(data)
    json.dump(json_data,my_file)

然后当你想要它回来时

json_data = json.load(open("file.txt"))

【讨论】:

  • 澄清-如果我的数据是“output.txt”,我该如何使用你的函数?
  • 将“file.txt”替换为“output.txt”
  • 我得到了一个与我之前尝试过 json.load() 类似的错误:ValueError: Expecting property name: line 1 column 2 (char 1)
  • 是的,您必须使用我首先向您展示的方法正确保存它
  • 我在使用 on_data 函数时遇到了另一个错误:TypeError: expected string or buffer。我再次认为它没有正确解析它,因为它将它视为一个巨大的字符串。除非我插入某种换行符?
猜你喜欢
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多