File size: 3,940 Bytes
dc13010
 
 
 
 
 
 
 
 
 
e62be7f
dc13010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9288bfa
dc13010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e62be7f
dc13010
 
 
 
 
 
 
94a47f5
 
 
 
 
 
 
 
dc13010
 
 
 
 
 
 
 
 
 
 
 
 
d13fb4b
 
 
dc13010
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94a47f5
 
dc13010
 
 
 
d13fb4b
e62be7f
dc13010
 
 
 
 
9288bfa
dc13010
 
9288bfa
dc13010
 
 
9288bfa
 
dc13010
 
 
 
 
 
 
 
9288bfa
d13fb4b
 
 
 
 
9288bfa
d13fb4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9288bfa
dc13010
 
e62be7f
 
 
 
 
 
 
 
d13fb4b
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
"""
This script converts the data from the raw data to CSV files.

Usage:
    make newsSpace
    python convert.py
"""

import csv
import html
import os
import sys

import pandas as pd

from bs4 import BeautifulSoup


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

OUTPUT_FILE_PATH = os.path.join("data", "all", "train.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, "html.parser")
    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")]

    output = "\n".join(lines)

    output = output.strip()

    if output == "null":
        return ""

    return output


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


def _clean_rank(rank):
    return int(rank)


def run():
    """
    Run the conversion process.
    """
    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),
        }

        if obj["text"]:
            rows.append(obj)

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

    save_categories(_categories)

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

    save_csv(rows)
    save_csv_categories(["World", "Sports", "Business", "Sci/Tech"], "top4-balanced", is_balanced=True)


def save_csv(rows, fname=OUTPUT_FILE_PATH):
    """
    Save the processed data into a CSV file.
    """
    os.makedirs(os.path.join("data", "all"), exist_ok=True)
    
    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 save_csv_categories(categories, config_name, is_balanced=True, **kwargs):
    """
    Filter the data by categories and split the data into training and testing
    sets. If is_balanced is True, the data will be balanced to size of the
    class with fewer examples.
    """
    df = pd.read_csv(OUTPUT_FILE_PATH)

    if is_balanced:
        dfs = []
        for category in categories:
            _df = df[df["category"] == category]
            dfs.append(_df)

        min_size = min([len(_df) for _df in dfs])

        dfs = [df.sample(min_size) for df in dfs]
        df = pd.concat(dfs)
    else:
        df = df[df["category"].isin(categories)]

    os.makedirs(f"data/{config_name}", exist_ok=True)

    df.to_csv(os.path.join("data", config_name, "train.csv"), index=False)


def save_categories(categories, fname="categories.txt"):
    """
    Save the categories into a text file.
    """
    with open(fname, "w") as f:
        for category in categories:
            f.write(category + os.linesep)


if __name__ == "__main__":
    run()