2016-04-24 10 views
1

いくつかのデータをCSVファイルに出力していますが、何らかの理由でデータを出力する方法が変わります。以下のコードは、オブジェクトをCSVファイルに出力する方法です。CSV出力が間違っています

@staticmethod 
def OutputCSV(csv_file): 
    posts = ApplicationModel.ApplicationModel.getTwitterObjects() 
    csv_columns = ['post','sentiment'] 
    with open(csv_file, 'w') as csvfile: 
     writer = csv.writer(csvfile) 
     writer.writerow(csv_columns) 
     for TwitterObject.TwitterObject in posts: 
      writer.writerow({ 
       TwitterObject.TwitterObject.post, 
       TwitterObject.TwitterObject.sentiment 
      }) 

以下のテキストは、出力されるCSVファイルのサンプルです。

post,sentiment 

b'@Angel4Rubio @ehillm @Arsenal welcott been shit since he came to the league.',neg 

pos,"b'Leicester closer to title, Arsenal held: Leicester City need just five points to complete a fairytale Premier ... '" 

pos,"b'Leicester closer to title, Arsenal held: Leicester City need just five points to complete a fairytale Premier ... '" 

pos,"b' @premierleague: ""I\'m slightly disappointed we didn\'t take all three points"" - Allardyce on #SUNARS\n\nMore: '" 

pos,"b'Leicester closer to title, Arsenal held: Leicester City need just five points to complete a fairytale Premier ... '" 

b' @MesutOzil1088: best. team. \xf0\x9f\x92\xaa\xf0\x9f\x8f\xbc\xf0\x9f\x98\x8e\n#yagunnersya #BeTheDifference #AFCvLCFC#Arsenal #bigpoints ',pos 

"b'Walcott, arteta, flamini, giroud and per to be sold. Bring in Hummells, Xhaka, Kante and Aubaumayang. #arsenal'",neg 

pos,b' @FootieFansKnow: Amongst all the madness there is always Hector #Arsenal #Sunderland #Wenger #UCLDraw #Topfour ' 
+0

アイテムの順序を優先させる場合は、その順序でソートする必要があります。 'sorted'関数を参照してください。 –

答えて

4

変更

writer.writerow({ 
      TwitterObject.TwitterObject.post, 
      TwitterObject.TwitterObject.sentiment 
     }) 

set

writer.writerow([ 
      TwitterObject.TwitterObject.post, 
      TwitterObject.TwitterObject.sentiment 
     ]) 

の要素は順不同です。したがって、行動。大規模なセット sの場合は x in sをプロファイルし、 x in lと比較してください( l = list(s))。前者のルックアップはO(1)であり、後者のO(n)である。これは、順序付けされていないハッシュ検索の利点の1つです。

+0

それは動作します!ありがとうございました! –

1

sortedで試してみてください:dictキーのような

@staticmethod 
def OutputCSV(csv_file): 
posts = ApplicationModel.ApplicationModel.getTwitterObjects() 
csv_columns = sorted(['post','sentiment']) 
with open(csv_file, 'w') as csvfile: 
    writer = csv.writer(csvfile) 
    writer.writerow(csv_columns) 
    for TwitterObject.TwitterObject in posts: 
     writer.writerow({ 
      TwitterObject.TwitterObject.post, 
      TwitterObject.TwitterObject.sentiment 
     }) 
関連する問題