2017-06-09 74 views
0

我是编程的初学者,但对于荷兰文本分类实验,我想将csv文件的每个实例(行)转换为单独的.txt文件,以便文本可以通过NLP工具进行分析。我的csv看起来像这样。使用Python将数据csv文件转换为不同的文本文件

enter image description here

正如你所看到的,每个实例在列“Taaloefening1”或列“Taaloefening2”文本。现在我需要将每个实例的文本保存在.txt文件中,并且文件的名称需要是id和标签。 我希望能通过使用csv模块编写Python脚本来自动完成此操作。我对如何将文本保存到.txt文件有一个想法,但我不知道如何将与文本匹配的id和标签作为文件名。 任何想法?

+1

的['csv'(https://docs.python.org/3/library/csv.html)模块包含了一些有用的工具。 – Kendas

+0

@Kendas,'csv'模块是否也适用于'xls'格式? –

+0

@ÉbeIsaac我不确定,但可以肯定的是,我会将文件导出为“csv”格式。 – Kendas

回答

1

csv.DictReader应该能够做你的需要:

from csv import DictReader 

INPUT_FILE = 'data.csv' 

with open(INPUT_FILE, 'rb') as csvfile: 
    reader = DictReader(csvfile) 
    for row in reader: 
     file_name = "{}_{}.txt".format(row["id"], row["Label"]) 
     if row["Taaloefening1"]:  # if this field is not empty 
      line = row["Taaloefening1"] + '\n' 
     elif row["Taaloefening2"]: 
      line = row["Taaloefening2"] + '\n' 
     else: 
      print("Both 'Taaloefening2' and 'Taaloefening2' empty on {}_{}. Skipping.".format(row["id"], row["Label"])) 
      continue 
     with open(file_name, 'w') as output: 
      output.write(line) 
相关问题