yelp_review / convert.py
1T Conte
first commit
e40c071
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()