File size: 2,185 Bytes
fffa9f9
4a223c0
fffa9f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1ae63
fffa9f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aec9efa
eb1ae63
aec9efa
 
 
 
 
 
fffa9f9
 
 
 
 
 
 
 
 
 
 
 
 
 
4a223c0
 
eb1ae63
 
4a223c0
 
 
 
 
 
 
 
 
 
fffa9f9
 
 
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
from datetime import datetime
from random import shuffle

import pandas as pd

from bs4 import BeautifulSoup


def parse_review(html):
    if html.startswith('"') and html.endswith('"'):
        html = html[1:-1]

    soup = BeautifulSoup(html, "lxml")
    text = soup.get_text()
    return text


def parse_rating(rating_str):
    rating = int(rating_str) - 1
    return rating


def parse_date(date_str):
    dt = datetime.strptime(date_str, "%B %d, %Y")

    iso_format_date = dt.strftime("%Y-%m-%d")

    return iso_format_date


def read_file(file_path):
    data = pd.read_csv(file_path, sep="\t")

    rows = []

    for _, row in data.iterrows():
        obj = {
            "id": row[0],
            "drugName": row[1],
            "condition": row[2],
            "review": parse_review(row[3]),
            "rating": parse_rating(row[4]),
            "date": parse_date(row[5]),
            "usefulCount": row[6],
        }
        rows.append(obj)

    return rows


def remap2sentiment(row):
    if row["rating"] <= 3:
        row["rating"] = 0
    else:
        row["rating"] = 1
    return row


def save(rows, file_path):
    df = pd.DataFrame(rows)
    df.to_csv(file_path, index=False)


def run():
    train_rows = read_file("drugsComTrain_raw.tsv")
    test_rows = read_file("drugsComTest_raw.tsv")
    all_rows = train_rows + test_rows

    save(train_rows, "train.csv")
    save(test_rows, "test.csv")
    save(all_rows, "complete.csv")

    # Extract only ratings 1, 2, 3, and 4 (negative reviews), and also
    # ratings 7, 8, 9, and 10 (positive reviews)
    negative_rows = [remap2sentiment(row) for row in all_rows if row["rating"] <= 3]
    positive_rows = [remap2sentiment(row) for row in all_rows if row["rating"] >= 6]
    positive_negative_rows = negative_rows + positive_rows
    shuffle(positive_negative_rows)
    save(positive_negative_rows, "positive_negative.csv")

    # Balance the dataset
    min_size = min(len(negative_rows), len(positive_rows))
    balanced_rows = negative_rows[:min_size] + positive_rows[:min_size]
    shuffle(balanced_rows)
    save(balanced_rows, "positive_negative_balanced.csv")


if __name__ == "__main__":
    run()