sentiment140 / convert.py
contemmcm's picture
Upload 2 files
3fbbc6d verified
import csv
import random
from io import StringIO
import pandas as pd
from bs4 import BeautifulSoup
def remap_polarity(row):
if row["label"] < 2:
row["label"] = 0
else:
row["label"] = 1
return row
def run():
rows = []
with open("training.1600000.processed.noemoticon.csv", "rb") as file:
lines = [line[:-1] for line in file.readlines()]
for line in lines:
try:
data = StringIO(line.decode("utf-8"))
except UnicodeDecodeError:
data = StringIO(line.decode("latin-1", errors="ignore"))
reader = csv.reader(data, delimiter=",")
for row in reader:
bs = BeautifulSoup(row[5], "lxml")
obj = {"label": int(row[0]), "text": bs.get_text()}
rows.append(obj)
df = pd.DataFrame(rows)
df.to_csv("complete.csv", index=False, encoding="utf-8")
polarity_rows = [remap_polarity(row) for row in rows if row["label"] != 2]
positive_rows = [row for row in polarity_rows if row["label"] == 1]
negative_rows = [row for row in polarity_rows if row["label"] == 0]
min_size = min(len(positive_rows), len(negative_rows))
polarity_rows = positive_rows[:min_size] + negative_rows[:min_size]
random.shuffle(polarity_rows)
df = pd.DataFrame(polarity_rows)
df.to_csv("polarity.csv", index=False, encoding="utf8")
if __name__ == "__main__":
run()