2013-07-14 10 views
1

我目前正在使用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"} 
] 
} 

回答

6

使用迭代石斑魚;該itertools module recipes list包括以下內容:

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) 

這使您可以遍歷您的tweets中的5000組:

for i, group in enumerate(grouper(input_tweets, 5000)): 
    with open('outputbatch_{}.json'.format(i), 'w') as outputfile: 
     json.dump(list(group), outputfile) 
+0

看起來真的很有趣。但我正在努力處理代碼的不同部分。我想我先閱讀json文件:「values = open('Tweets.json')。read()」。你能詳細介紹一下不同的參數嗎?謝謝 – Tom

+0

差不多; 'json.load(openfileobject)'會起作用。 –

+0

好的。謝謝!什麼是石斑魚和input_tweets參數? – Tom

0

我覺得你的第一個想法是好的。只需迭代你得到的所有推文,將它們保存在一個臨時數組中,並跟蹤每次推文增加一個索引。總是噹噹前索引模5000等於0時,調用一種方法將字符串格式的推文轉換並將其保存在文件名中具有索引的文件中。如果你到達推文的末尾,在最後的休息時也要這樣做。

我不確定我是否可以回答你的問題。如果你正在尋找一些更復雜的東西,只需google關於hadoop json-file splitter。

相關問題