File size: 1,733 Bytes
9f770cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv

from random import shuffle

import pandas as pd

NEGATIVE = 0
POSITIVE = 1

ROTTEN = 0
FRESH = 1


def parse_is_top_critic(is_top_critic):
    return is_top_critic == "True"


def parse_score_sentiment(score):
    if score == "NEGATIVE":
        return NEGATIVE
    if score == "POSITIVE":
        return POSITIVE
    raise ValueError(f"Unknown score sentiment: {score}")


def parse_review_state(review_state):
    if review_state == "rotten":
        return ROTTEN
    if review_state == "fresh":
        return FRESH

    raise ValueError(f"Unknown review state: {review_state}")


def run():
    with open("rotten_tomatoes_movie_reviews.csv") as f:
        reader = csv.DictReader(f)
        rows = list(reader)

    positive_rows = []
    negative_rows = []

    for row in rows:
        row["isTopCritic"] = parse_is_top_critic(row["isTopCritic"])
        row["scoreSentiment"] = parse_score_sentiment(row["scoreSentiment"])
        row["reviewState"] = parse_review_state(row["reviewState"])

        if row["scoreSentiment"] == POSITIVE:
            positive_rows.append(row)
        else:
            negative_rows.append(row)

    # Save rows to csv file called original.csv
    pd.DataFrame(rows).to_csv("original.csv", index=False)

    shuffle(positive_rows)
    shuffle(negative_rows)

    # Generate the balanced datasets
    balanced_size = min(len(positive_rows), len(negative_rows))
    balanced_rows = []
    for i in range(0, balanced_size):
        balanced_rows.append(positive_rows[i])
        balanced_rows.append(negative_rows[i])

    # Save balanced rows to csv file called balanced.csv
    pd.DataFrame(balanced_rows).to_csv("balanced.csv", index=False)


if __name__ == "__main__":
    run()