Reputation: 596
I'm printing out to a csv file like this:
bdictionary = ## bdictionary is a big list of tuples
w = csv.writer(open("testnucsv.csv", "w"))
for sent in bdictionary:
w.writerow(sent)
And it prints out perfectly fine and looks like this:
(u'My', u'D') (u'dog', u'N')............... (u'The', u'D') ............................
How can I print it out like this
My D dog N The D
This is what I tried, and it isn't working. It splits up every charachter:
w = csv.writer(open("testnucsv.csv", "w"))
for sent in bdictionary:
sent = ''.join(str(v) for v in sent)
w.writerow(sent)
Upvotes: 4
Views: 1040
Reputation: 180441
Wrap it in a list, writerow expects an iterable so it iterates over your string splitting it into single characters:
sent = [' '.join(" ".join(v) for v in sent)]
You also need to join the strings in the tuple as above not call str on the tuple i.e:
t = [(u'My', u'D'), (u'dog', u'N')]
print(" ".join([" ".join(v) for v in t]))
My D dog N
You could also just use file.write and pass it the joined string:
with open("testnucsv.csv", "w") as f:
for sent in bdictionary:
f.write(" ".join([" ".join(v) for v in sent])+"\n")
Upvotes: 2