File size: 1,413 Bytes
b80e9f0 3fbbc6d b80e9f0 3fbbc6d b80e9f0 3fbbc6d b80e9f0 3fbbc6d b80e9f0 3fbbc6d b80e9f0 3fbbc6d b80e9f0 |
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 |
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()
|