【问题标题】:efficient method to read and store data which is in JSON读取和存储 JSON 数据的有效方法
【发布时间】:2019-05-13 07:31:00
【问题描述】:
tweets_data = []
print('Opening file')
tweets_file = open('twitter_data.txt') #Its a file which has twitter data in JSON
start_time = time.time()
print('List generation in process')
for line in tweets_file:
   try:
      tweet = json.loads(line)
      tweets_data.append(tweet)
   except:
      continue
tweets_file.close()
print(len(tweets_data))

我正在使用上面的代码创建一个列表,该列表作为 twitter 数据(通过 twitter api 流获得大约 3GB),但我的程序运行时间超过 3 小时。我需要一种有效的方法来做到这一点,因为我想使用这个列表来构建一个数据框。

【问题讨论】:

    标签: python json pandas twitter time


    【解决方案1】:

    如果您将 try except 子句移到这样的生成器函数中,它可能会有所帮助:

    def readline(tweets_file):
        for line in tweets_file:
            try:
               tweet = json.loads(line)
               yield tweet
           except:
               continue
    

    这样做使它不会创建一个列表,所以你不能对它执行 len(),但你仍然可以迭代它而不需要在内存中构建一个完整的列表。当您遍历生成器时,它将一次产生一个结果。如果您仍然想要一个 len,您可以将其转换为一个列表,例如:

    len(list(readline(tweets_file)))
    

    或者你可以遍历生成器并计数,例如:

    counter = 0
    for json_result in realine(tweets_file):
        counter += 1
    

    【讨论】:

      【解决方案2】:

      我不确定

      tweets_data = []
      print('Opening file')
      tweets_file = open('twitter_data.txt') #Its a file which has twitter data in JSON
      start_time = time.time()
      append = tweets_data.append
      print('List generation in process')
      for line in tweets_file:
          try:
              tweet = json.loads(line)
              append(tweet)
          except:
              continue
      tweets_file.close()
      print(len(tweets_data))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-03-09
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-21
        • 2017-01-06
        • 2012-08-14
        相关资源
        最近更新 更多