|
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) |
|
|
|
|
|
pd.DataFrame(rows).to_csv("original.csv", index=False) |
|
|
|
shuffle(positive_rows) |
|
shuffle(negative_rows) |
|
|
|
|
|
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]) |
|
|
|
|
|
pd.DataFrame(balanced_rows).to_csv("balanced.csv", index=False) |
|
|
|
|
|
if __name__ == "__main__": |
|
run() |
|
|