使用 Python 将数据 csv 文件转换为不同的文本文件
Data csv file into different text files with Python
我是编程初学者,但对于荷兰语文本分类实验,我想将 csv 文件的每个实例(行)转换为单独的 .txt 文件,以便 NLP 工具可以分析文本.我的 csv 看起来像这样。
如您所见,每个实例在 'Taaloefening1' 列或 'Taaloefening2' 列中都有文本。现在我需要将每个实例的文本保存在一个 .txt 文件中,文件名需要是 id 和标签。
我希望我可以通过使用 csv 模块在 Python 中编写脚本来自动完成此操作。我知道如何将文本保存到 .txt 文件中,但我不知道如何将与文本匹配的 id 和标签作为文件名。
有什么想法吗?
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)
我是编程初学者,但对于荷兰语文本分类实验,我想将 csv 文件的每个实例(行)转换为单独的 .txt 文件,以便 NLP 工具可以分析文本.我的 csv 看起来像这样。
如您所见,每个实例在 'Taaloefening1' 列或 'Taaloefening2' 列中都有文本。现在我需要将每个实例的文本保存在一个 .txt 文件中,文件名需要是 id 和标签。 我希望我可以通过使用 csv 模块在 Python 中编写脚本来自动完成此操作。我知道如何将文本保存到 .txt 文件中,但我不知道如何将与文本匹配的 id 和标签作为文件名。 有什么想法吗?
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)