【发布时间】:2015-03-05 06:31:19
【问题描述】:
我正在编写一个代码,我需要将 txt 文件中的句子数据集转换为 csv 文件。这是我的代码,它工作正常,将输入 txt 文件转换为 csv 文件的格式。
但是,我无法制作输出 csv 文件。我是 python 编程的新手,所以我还不知道如何解决它。
这是我的代码:
def txtTOcsv():
output_csv = []
with open("dataset.txt", "r") as myfile:
lines = myfile.readlines()
for line in lines:
row = line.split()
for i in row[1:]:
tokens = (row[0],i)
print tokens
output_csv.append(tokens)
with open(output_csv,'w') as out_file:
csv.writer(out_file)
它工作正常,直到
print tokens
并按照我的需要打印所有列之间带有逗号的列。但是当它转到将输出保存在 csv 文件中的行时。它给出了这个错误:
with open(output_csv,'w') as out_file:
TypeError: coercing to Unicode: need string or buffer, list found
任何帮助将不胜感激。谢谢。
【问题讨论】:
-
这条
output_csv.append(tokens)行适合您吗?发布tokens变量的值。 -
是的,它确实有效。它输出这种格式的东西:` ('------', '-----------') ` @AvinashRaj
标签: python python-2.7 csv unicode