File size: 1,335 Bytes
fffa9f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
60
61
62
63
64
65
66
67
from datetime import datetime

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 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")


if __name__ == "__main__":
    run()