Python CSV输出空白单元格

时间:2015-04-23 01:06:08

标签: python csv nltk

我正在尝试将我的python代码的确切shell输出写入csv文件(包括空白字段)。我的Python输出看起来像这样。我试图解决这个问题,但由于某种原因,我得到的输出看起来像这样。

contractNN
develop NN
manag   NN
order   NN
parti   NN
suitabl NN
supplier NN
work    NN

所需的CSV输出

[[(u'contract', 'NN'), (u'develop', 'NN'), (u'manag', 'NN'), (u'order', 'NN'), (u'parti', 'NN'), (u'suitabl', 'NN'), (u'supplier', 'NN'), (u'work', 'NN')]]
[[(u'microsoft', 'NN')]]
[[(u'hadoop', 'NN')]]
[[]]
[[(u'python', 'NN'), (u'python', 'NN')]]
[[]]
[[]]

我的Python代码

import csv
import nltk
from nltk import pos_tag
from nltk.stem.snowball import SnowballStemmer
from nltk import stem
import numpy as np

output_file = open('examp_output.csv', 'w')
datawriter = csv.writer(output_file)

"""Bunch of NLTK Code"""

    print [m]

    datawriter.writerows(m)
output_file.close()

1 个答案:

答案 0 :(得分:0)

如何使用而不是使用CSVWriter

import os
output_file = open('example.txt','w') #use 'a' instead of 'w' to append  instead of overwrite the text file if you're doing this in a loop
output_file.write(data_out)
os.rename('example.txt', 'example.csv')