我有以下完全工作的代码
考虑到我目前分析了1,400个JSON(大约1.5Gb),运行代码需要相当长的时间。请建议是否有一个合理的方法来优化代码,以提高其速度。谢谢!
import os
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
tweets = []
for dirs, subdirs, files in os.walk('/Users/mymac/Documents/Dir'):
for file in files:
if file.endswith('.json'):
print(file)
for line in open(file) :
try:
tweet = json.loads(line)
tweets.append(tweet)
except:
continue
tweet = tweets[0]
ids = [tweet['id_str'] for tweet in tweets if 'id_str' in tweet]
text = [tweet['text'] for tweet in tweets if 'text' in tweet]
lang = [tweet['lang'] for tweet in tweets if 'lang' in tweet]
geo = [tweet['geo'] for tweet in tweets if 'geo' in tweet]
place = [tweet['place'] for tweet in tweets if 'place' in tweet]
df=pd.DataFrame({'Ids':pd.Index(ids),
'Text':pd.Index(text),
'Lang':pd.Index(lang),
'Geo':pd.Index(geo),
'Place':pd.Index(place)})
df
发布于 2017-03-30 07:03:41
只是简单地考虑一下:
import os
matplotlib
和numpy
,所以import
s可以去tweet = tweets[0]
是无用的with
关键字两个优化:
print(file)
。这可能是你能做的一个最好的优化。像这样的东西怎么样(没有测试!):
from collections import defaultdict
elements_keys = ['ids', 'text', 'lang', 'geo', 'place']
elements = defaultdict(list)
for dirs, subdirs, files in os.walk('/Users/mymac/Documents/Dir'):
for file in files:
if file.endswith('.json'):
with open(file, 'r') as input_file:
for line in input_file:
try:
tweet = json.loads(line)
for key in elements_keys:
elements[key].append(tweet[key])
except:
continue
df=pd.DataFrame({'Ids': pd.Index(elements['id']),
'Text': pd.Index(elements['text']),
'Lang': pd.Index(elements['lang']),
'Geo': pd.Index(elements['geo']),
'Place': pd.Index(elements['place'])})
df
https://codereview.stackexchange.com/questions/159303
复制相似问题