gpt4 book ai didi

python - Writing multiple JSON to CSV in Python - 字典到 CSV

转载 作者:太空宇宙 更新时间:2023-11-04 06:02:21 24 4
gpt4 key购买 nike

我正在使用 Tweepy 流式传输推文,并希望以 CSV 格式记录它们,以便我可以使用它们或稍后将它们加载到数据库中。请记住,我是一个菜鸟,但我确实知道有多种方法可以处理这个问题(非常欢迎提出建议)。

长话短说,我需要将多个 Python 词典转换并附加到一个 CSV 文件中。我已经进行了研究 (How do I write a Python dictionary to a csv file?) 并尝试使用 DictWriter 和 writer 方法进行此操作。

但是,还有一些事情需要完成:

1) 仅将 key 作为 header 写入一次。

2) 随着新推文的流式传输,需要在不覆盖先前行的情况下附加值。

3) 如果值缺失记录NULL。

4) 跳过/修复 ascii 编解码器错误。

这是我希望最终得到的格式(每个值都在其单独的单元格中):

Header1_Key_1 Header2_Key_2 Header3_Key_3...

Row1_Value_1 Row1_Value_2 Row1_Value_3...

Row2_Value_1 Row2_Value_2 Row2_Value_3...

Row3_Value_1 Row3_Value_2 Row3_Value_3...

Row4_Value_1 Row4_Value_2 Row4_Value_3...

这是我的代码:

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import csv
import json

consumer_key="XXXX"
consumer_secret="XXXX"
access_token="XXXX"
access_token_secret="XXXX"

class StdOutListener(StreamListener):

def on_data(self, data):
json_data = json.loads(data)

data_header = json_data.keys()
data_row = json_data.values()

try:
with open('csv_tweet3.csv', 'wb') as f:
w = csv.DictWriter(f, data_header)
w.writeheader(data_header)
w.writerow(json_data)
except BaseException, e:
print 'Something is wrong', str(e)

return True

def on_error(self, status):
print status

if __name__ == '__main__':
l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

stream = Stream(auth, l)
stream.filter(track=['world cup'])

提前致谢!

最佳答案

我用 facebook 的图形 API(facepy 模块)做了类似的事情!

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import csv
import json

consumer_key="XXXX"
consumer_secret="XXXX"
access_token="XXXX"
access_token_secret="XXXX"

class StdOutListener(StreamListener):
_headers = None
def __init__(self,headers,*args,**keys):
StreamListener.__init__(self,*args,**keys)
self._headers = headers

def on_data(self, data):
json_data = json.loads(data)

#data_header = json_data.keys()
#data_row = json_data.values()

try:
with open('csv_tweet3.csv', 'ab') as f: # a for append
w = csv.writer(f)
# write!
w.writerow(self._valToStr(json_data[header])
if header in json_data else ''
for header in self._headers)
except Exception, e:
print 'Something is wrong', str(e)

return True

@static_method
def _valToStr(o):
# json returns a set number of datatypes - parse dependingly
# https://docs.python.org/2/library/json.html#encoders-and-decoders
if type(o)==unicode: return self._removeNonASCII(o)
elif type(o)==bool: return str(o)
elif type(o)==None: return ''
elif ...
...

def _removeNonASCII(s):
return ''.join(i if ord(i)<128 else '' for i in s)

def on_error(self, status):
print status

if __name__ == '__main__':
headers = ['look','at','twitter','api',
'to','find','all','possible',
'keys']

# initialize csv file with header info
with open('csv_tweet3.csv', 'wb') as f:
w = csv.writer(headers)

l = StdOutListener(headers)
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

stream = Stream(auth, l)
stream.filter(track=['world cup'])

它还没有准备好复制和粘贴,但它足够清晰,您应该能够完成它。
为了提高性能,您可能希望打开文件,写入多条记录,然后关闭文件。这样你就不会一直打开、初始化 csv 编写器、附加然后关闭文件。我不熟悉 tweepy API,所以我不确定它到底是如何工作的 - 但它值得研究。

如果您遇到任何麻烦,我很乐意提供帮助 - 享受吧!

关于python - Writing multiple JSON to CSV in Python - 字典到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24155319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com