|
from datetime import datetime |
|
from random import shuffle |
|
|
|
import pandas as pd |
|
|
|
from bs4 import BeautifulSoup |
|
|
|
|
|
def parse_review(html): |
|
if html.startswith('"') and html.endswith('"'): |
|
html = html[1:-1] |
|
|
|
soup = BeautifulSoup(html, "lxml") |
|
text = soup.get_text() |
|
return text |
|
|
|
|
|
def parse_rating(rating_str): |
|
rating = int(rating_str) |
|
return rating |
|
|
|
|
|
def parse_date(date_str): |
|
dt = datetime.strptime(date_str, "%B %d, %Y") |
|
|
|
iso_format_date = dt.strftime("%Y-%m-%d") |
|
|
|
return iso_format_date |
|
|
|
|
|
def read_file(file_path): |
|
data = pd.read_csv(file_path, sep="\t") |
|
|
|
rows = [] |
|
|
|
for _, row in data.iterrows(): |
|
obj = { |
|
"id": row[0], |
|
"drugName": row[1], |
|
"condition": row[2], |
|
"review": parse_review(row[3]), |
|
"rating": parse_rating(row[4]), |
|
"date": parse_date(row[5]), |
|
"usefulCount": row[6], |
|
} |
|
rows.append(obj) |
|
|
|
return rows |
|
|
|
|
|
def remap2sentiment(row): |
|
if row["rating"] <= 4: |
|
row["rating"] = 0 |
|
else: |
|
row["rating"] = 1 |
|
return row |
|
|
|
|
|
def save(rows, file_path): |
|
df = pd.DataFrame(rows) |
|
df.to_csv(file_path, index=False) |
|
|
|
|
|
def run(): |
|
train_rows = read_file("drugsComTrain_raw.tsv") |
|
test_rows = read_file("drugsComTest_raw.tsv") |
|
all_rows = train_rows + test_rows |
|
|
|
save(train_rows, "train.csv") |
|
save(test_rows, "test.csv") |
|
save(all_rows, "complete.csv") |
|
|
|
|
|
|
|
negative_rows = [remap2sentiment(row) for row in all_rows if row["rating"] <= 4] |
|
positive_rows = [remap2sentiment(row) for row in all_rows if row["rating"] >= 7] |
|
positive_negative_rows = negative_rows + positive_rows |
|
shuffle(positive_negative_rows) |
|
save(positive_negative_rows, "positive_negative.csv") |
|
|
|
|
|
min_size = min(len(negative_rows), len(positive_rows)) |
|
balanced_rows = negative_rows[:min_size] + positive_rows[:min_size] |
|
shuffle(balanced_rows) |
|
save(balanced_rows, "positive_negative_balanced.csv") |
|
|
|
|
|
if __name__ == "__main__": |
|
run() |
|
|