File size: 1,259 Bytes
e40c071
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import json
import random

import pandas as pd


def parse_review(line):
    d = json.loads(line)
    d.pop("review_id")
    d.pop("user_id")
    d.pop("business_id")
    d["stars"] = int(d["stars"]) - 1  # from 0 to 4

    return d


def remap2polarity(row):
    if row["stars"] in [0, 1]:
        row["stars"] = 0
    elif row["stars"] in [3, 4]:
        row["stars"] = 1
    else:
        raise ValueError("Invalid value")

    return row


def run():
    rows = []

    with open(
        "yelp_dataset/yelp_academic_dataset_review.json", "r", encoding="utf8"
    ) as file:
        lines = file.readlines()

    for line in lines:
        obj = parse_review(line)
        rows.append(obj)

    df = pd.DataFrame(rows)
    df.to_parquet("reviews.parquet")

    # polarity
    polarity_rows = [remap2polarity(row) for row in rows if row["stars"] != 2]

    positive = [row for row in polarity_rows if row["stars"] == 1]
    negative = [row for row in polarity_rows if row["stars"] == 0]
    min_size = min(len(positive), len(negative))

    polarity_rows = positive[:min_size] + negative[:min_size]
    random.shuffle(polarity_rows)

    df = pd.DataFrame(polarity_rows)
    df.to_parquet("reviews_polarity.parquet")


if __name__ == "__main__":
    run()