使用Python将数据csv文件转换为不同的文本文件

时间:2017-06-09 08:27:24

标签: python csv nlp text-classification

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

enter image description here

如您所见,每个实例在“Taaloefening1”列或“Taaloefening2”列中都有文本。现在我需要将每个实例的文本保存在.txt文件中,文件名必须是id和标签。 我希望通过使用csv模块在Python中编写脚本来自动完成此操作。我知道如何将文本保存到.txt文件中,但我不知道如何将与文本匹配的id和标签作为文件名。 有什么想法吗?

1 个答案:

答案 0 :(得分: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)