File size: 2,125 Bytes
1e73de8
 
 
 
 
 
 
 
 
 
 
 
80a91d5
1e73de8
6f0523f
80a91d5
 
1e73de8
 
 
 
 
 
 
fc90f11
 
1e73de8
 
 
 
 
 
 
 
 
975f297
 
 
1e73de8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""
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()