我目前正在使用Twitter帖子的感受分析的項目。 我正在用Sentiment140對Tweets進行分類。使用該工具,我可以每天分類高達1,000,000條推文,並收集了大約750,000條推文。所以這應該沒問題。 唯一的問題是,我可以一次發送最多15,000條推文到JSON批量分類。用Python拆分等於/小於零的JSON文件
我的整個代碼已設置並正在運行。唯一的問題是我的JSON文件現在包含全部750,000個推文。
因此,我的問題:什麼是將JSON拆分爲具有相同結構的較小文件的最佳方式?我寧願在Python中這樣做。
我想過迭代文件。但是,如何在代碼中指定它應該在例如5,000個元素之後創建一個新文件?
我很想得到一些提示什麼是最合理的方法。謝謝!
編輯:這是我現在的代碼。
import itertools
import json
from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
# Open JSON file
values = open('Tweets.json').read()
#print values
# Adjust formatting of JSON file
values = values.replace('\n', '') # do your cleanup here
#print values
v = values.encode('utf-8')
#print v
# Load JSON file
v = json.loads(v)
print type(v)
for i, group in enumerate(grouper(v, 5000)):
with open('outputbatch_{}.json'.format(i), 'w') as outputfile:
json.dump(list(group), outputfile)
的輸出給出:
["data", null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, ...]
在稱爲文件: 「outputbatch_0.json」
編輯2:這是JSON的結構。
{
"data": [
{
"text": "So has @MissJia already discussed this Kelly Rowland Dirty Laundry song? I ain't trying to go all through her timelime...",
"id": "1"
},
{
"text": "RT @UrbanBelleMag: While everyone waits for Kelly Rowland to name her abusive ex, don't hold your breath. But she does say he's changed: ht\u00e2\u20ac\u00a6",
"id": "2"
},
{
"text": "@Iknowimbetter naw if its weak which I dont think it will be im not gonna want to buy and up buying Kanye or even Kelly Rowland album lol",
"id": "3"}
]
}
看起來真的很有趣。但我正在努力處理代碼的不同部分。我想我先閱讀json文件:「values = open('Tweets.json')。read()」。你能詳細介紹一下不同的參數嗎?謝謝 – Tom
差不多; 'json.load(openfileobject)'會起作用。 –
好的。謝謝!什麼是石斑魚和input_tweets參數? – Tom