20_newsgroups / convert.py
Marcio Monteiro
feat: unsplitting data into train and test set
f03698d
"""
This script converts the data from the raw data folder to a CSV file.
Usage:
make 20_newsgroups
python convert.py
"""
import csv
import os
import re
DATASET_PATH = "20_newsgroups"
OUTPUT_FILE = "20newsgroups.csv"
TRAIN_OUTPUT_FILE = "train.csv"
TEST_OUTPUT_FILE = "test.csv"
def run():
"""
Main function to run the script.
"""
class_list = os.listdir(DATASET_PATH)
class_list.sort()
rows = []
for class_name in class_list:
doc_list = os.listdir(os.path.join(DATASET_PATH, class_name))
for doc_name in doc_list:
doc = parse_document(read_document(class_name, doc_name))
doc["label"] = class_list.index(class_name)
# Skip empty documents
if doc["text"]:
rows.append(doc)
save_csv(rows)
def read_document(class_name, doc_name):
"""
Read the content of a document in the corpus.
"""
doc_path = os.path.join(DATASET_PATH, class_name, doc_name)
with open(doc_path, "r", encoding="ISO-8859-15") as fin:
content = fin.read()
return content
def save_csv(rows, fname=OUTPUT_FILE):
"""
Save the processed data into a CSV file.
"""
with open(fname, "w", encoding="utf8") as f:
writer = csv.DictWriter(f, fieldnames=rows[0].keys())
writer.writeheader()
for row in rows:
writer.writerow(row)
def parse_document(doc):
"""
Parses a document into a dictionary
"""
header_start = 0
header_end = doc.find("\n\n")
body_start = header_end + 2
header = doc[header_start:header_end]
body = doc[body_start:]
return {
"from": parse_header(header, "From"),
"subject": parse_header(header, "Subject"),
"organization": parse_header(header, "Organization"),
"text": body,
}
def parse_header(header, param):
"""
Obtains the value of a parameter from the header
"""
try:
return re.search(param + r": (.+)\n", header, re.IGNORECASE).group(1)
except AttributeError:
return None
if __name__ == "__main__":
run()