2017-02-21 37 views
2

我有一個存儲在推文中的詞典列表,我試圖用writerows方法將這些詞典寫入一個csv文件。如何將多級詞典的列表寫入csv

樣本列表看起來是這樣的:

[{'sentiment': 'Unknown', 'date': datetime.datetime(2013, 1, 1, 5, 31, 32), 'body': 'mcd brk b'}, 
{'sentiment': 'Unknown', 'date': datetime.datetime(2013, 1, 1, 6, 55, 23), 'body': 'co hihq'}, 
{'sentiment': {'basic': 'Bullish'}, 'date': datetime.datetime(2013, 1, 1, 7, 36, 32), 'body': 'new year bac'}] 

這裏sentiment鍵有任何一個一級或兩級。我正在嘗試將這些字典寫成csv格式,以便我只將這些密鑰的值設置爲'未知'或'看漲'以上。

file = open('BAC.csv','w') 
keys=tweets[0].keys() 
dict_writer=csv.DictWriter(file,keys) 
dict_writer.writerows(tweets) 

我得到了下面的格式

Unknown,2013-01-01 05:31:32,mcd brk b 
Unknown,2013-01-01 06:55:23,co hihq 
{'basic': 'Bullish'},2013-01-01 07:36:32,mnew year bac 

的CSV文件,但我需要它作爲

Unknown,2013-01-01 05:31:32,mcd brk b 
Unknown,2013-01-01 06:55:23,co hihq 
Bullish,2013-01-01 07:36:32,mnew year bac 

有沒有簡單的方法來做到這一點?在很多情況下,這個水平會上升到五,但類似的交易只需要價值。

回答

0

您需要編寫一個函數來平滑這些情感值。

如果您在每個關卡中只有一個元素,就可以使用類似的東西。

def flatten(row, field): 
    if isinstance(row[field], dict): 
     row[field] = row[field].values()[0] 
     return flatten(row, field) 
    return row 

那麼你就需要將其寫入到CSV之前調用每行此方法。

tweets = [{'sentiment': 'Unknown', 'date': datetime.datetime(2013, 1, 1, 5, 31, 32), 'body': 'mcd brk b'}, 
     {'sentiment': 'Unknown', 'date': datetime.datetime(2013, 1, 1, 6, 55, 23), 'body': 'co hihq'}, 
     {'sentiment': {'basic': {'text': 'Bullish' } }, 'date': datetime.datetime(2013, 1, 1, 7, 36, 32), 'body': 'new year bac'}] 

print [flatten(row, 'sentiment') for row in tweets] 

輸出

[{'date': datetime.datetime(2013, 1, 1, 5, 31, 32), 'body': 'mcd brk b', 'sentiment': 'Unknown'}, 
{'date': datetime.datetime(2013, 1, 1, 6, 55, 23), 'body': 'co hihq', 'sentiment': 'Unknown'}, 
{'date': datetime.datetime(2013, 1, 1, 7, 36, 32), 'body': 'new year bac', 'sentiment': 'Bullish'}]