我正在打印到这样的csv文件:
bdictionary = ## bdictionary is a big list of tuples
w = csv.writer(open("testnucsv.csv", "w"))
for sent in bdictionary:
w.writerow(sent)
它的打印效果非常好,看起来像这样:
('我',你'')(u'dog',u'N')............... (你','u'D')............................
如何将其打印出来
我的D狗N. D
这就是我尝试过的,但它无法正常工作。它分裂了每个字符:
w = csv.writer(open("testnucsv.csv", "w"))
for sent in bdictionary:
sent = ''.join(str(v) for v in sent)
w.writerow(sent)
答案 0 :(得分:2)
将它包装在一个列表中,写作者期望一个可迭代的,所以它迭代你的字符串,将它分成单个字符:
sent = [' '.join(" ".join(v) for v in sent)]
你还需要加入元组中的字符串,而不是在元组上调用str,即:
t = [(u'My', u'D'), (u'dog', u'N')]
print(" ".join([" ".join(v) for v in t]))
My D dog N
您也可以使用file.write并将连接的字符串传递给它:
with open("testnucsv.csv", "w") as f:
for sent in bdictionary:
f.write(" ".join([" ".join(v) for v in sent])+"\n")