cathw commited on
Commit
1455fc8
1 Parent(s): 82ae337

Upload csvtransformerjson.py

Browse files
Files changed (1) hide show
  1. csvtransformerjson.py +69 -0
csvtransformerjson.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ import pandas as pd
3
+
4
+ class CSVtoJSONTransformer:
5
+ def __init__(self, csv_reader):
6
+ self.csv_reader = csv_reader
7
+
8
+ def transform_to_json(self):
9
+ df = pd.DataFrame(self.csv_reader) # Convert csv_reader to DataFrame
10
+ df["Author"] = df["Author"].replace({pd.NA: None})
11
+ df["Comment Body"] = df["Comment Body"].replace({pd.NA: None})
12
+
13
+ # Define an empty list to store the transformed data
14
+ transformed_data = []
15
+
16
+ # Group the DataFrame by the 'Subreddit' column
17
+ grouped_df = df.groupby('Subreddit')
18
+
19
+ # Iterate through each subreddit group
20
+ for subreddit, group in grouped_df:
21
+ subreddit_data = {
22
+ "Subreddit": subreddit,
23
+ "Posts": []
24
+ }
25
+
26
+ # Iterate through each row in the subreddit group
27
+ for index, row in group.iterrows():
28
+ post_title = row['Post Title']
29
+ comment_body = row['Comment Body']
30
+ timestamp = row['Timestamp']
31
+ upvotes = row['Upvotes']
32
+ ID = row['ID']
33
+ author = row['Author']
34
+ replies = row['Number of Replies']
35
+
36
+ # Check if the post title already exists under the subreddit
37
+ post_exists = False
38
+ for post in subreddit_data["Posts"]:
39
+ if post['PostTitle'] == post_title:
40
+ post_exists = True
41
+ post['Comments'].append({
42
+ "CommentID": ID,
43
+ "Author": author,
44
+ "CommentBody": comment_body,
45
+ "Timestamp": timestamp,
46
+ "Upvotes": upvotes,
47
+ "NumberofReplies": replies
48
+ })
49
+ break
50
+
51
+ # If the post title does not exist, create a new entry
52
+ if not post_exists:
53
+ subreddit_data["Posts"].append({
54
+ "PostID": len(subreddit_data["Posts"]) + 1,
55
+ "PostTitle": post_title,
56
+ "Comments": [{
57
+ "CommentID": ID,
58
+ "Author": author,
59
+ "CommentBody": comment_body,
60
+ "Timestamp": timestamp,
61
+ "Upvotes": upvotes,
62
+ "NumberofReplies": replies
63
+ }]
64
+ })
65
+
66
+ # Append the subreddit data to the transformed data list
67
+ transformed_data.append(subreddit_data)
68
+
69
+ return transformed_data