File size: 2,963 Bytes
dc13010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""
This script converts the data from the raw data to CSV files.

Usage:
    make newsSpace
    python convert.py
"""

import csv
import html
import sys

import pandas as pd

from bs4 import BeautifulSoup

from sklearn.model_selection import train_test_split

HEADER = [
    "source",
    "url",
    "title",
    "image",
    "category",
    "description",
    "rank",
    "pubdate",
]

OUTPUT_FILE = "ag_news.csv"
TRAIN_OUTPUT_FILE = "train.csv"
TEST_OUTPUT_FILE = "test.csv"


def _clean_text(text):
    text = text.replace("\\\n", "\n")
    text = html.unescape(text)

    if text == "\\N":
        return ""

    return text


def _clean_html(text):
    html_code = _clean_text(text)
    html_code.replace("</p>", "\n\n</p>")
    html_code.replace("<br>", "\n")

    soup = BeautifulSoup(html_code, "lxml")
    text = soup.get_text(separator=" ")

    text = text.replace(" \n", "\n").replace("\n ", "\n")

    # remove extra spaces at the beginning of the text
    lines = [line.strip() for line in text.split("\n")]

    return "\n".join(lines)


def _clean_image(image):
    if image == "none":
        return None
    return image


def _clean_rank(rank):
    return int(rank)


def run():
    rows = []
    categories = set()

    with open("newsSpace", encoding="ISO-8859-15") as f:
        doc = f.read()

    for row in doc.split("\t\\N\n"):
        if not row:
            continue

        row = row.replace("\\\t", "")

        try:
            source, url, title, image, category, description, rank, pubdate = row.split(
                "\t"
            )
        except ValueError:
            print(repr(row))
            sys.exit(1)

        categories.add(category)

        obj = {
            "source": source,
            "url": url,
            "title": _clean_text(title),
            "image": _clean_image(image),
            "category": category,
            "description": _clean_text(description),
            "rank": _clean_rank(rank),
            "pubdate": pubdate,
            "text": _clean_html(description),
        }

        rows.append(obj)

    # Add a label to each row
    _categories = list(categories)
    _categories.sort()

    for row in rows:
        row["label"] = _categories.index(row["category"])

    save_csv(rows)
    split_csv_train_test(test_size=0.2, random_state=42)


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 split_csv_train_test(**kwargs):
    """
    Split the data into training and testing sets.
    """
    df = pd.read_csv(OUTPUT_FILE)
    train_df, test_df = train_test_split(df, **kwargs)
    train_df.to_csv(TRAIN_OUTPUT_FILE, index=False)
    test_df.to_csv(TEST_OUTPUT_FILE, index=False)


if __name__ == "__main__":
    run()