我正在将一些数据输出到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 :(得分:5)
更改
writer.writerow({
TwitterObject.TwitterObject.post,
TwitterObject.TwitterObject.sentiment
})
到
writer.writerow([
TwitterObject.TwitterObject.post,
TwitterObject.TwitterObject.sentiment
])
像set
个键这样的{p> dict
元素是无序的。因此行为。您可以为大型集x in s
分析s
,并将其与x in l
进行比较,其中l = list(s)
。前者的查找是O(1),而后者是O(n)。这是无序散列查找的优点之一。
答案 1 :(得分:1)
尝试sorted
:
@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
})