cathw commited on
Commit
ea6f77f
1 Parent(s): b652229

Upload csvtransformerjson.py

Browse files
Files changed (1) hide show
  1. csvtransformerjson.py +71 -0
csvtransformerjson.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ next(self.csv_reader) # Skip header if present
10
+ df = pd.DataFrame(self.csv_reader) # Convert csv_reader to DataFrame
11
+ df["Author"] = df["Author"].replace({pd.NA: None})
12
+ df["Comment Body"] = df["Comment Body"].replace({pd.NA: None})
13
+
14
+ transformed_data = []
15
+
16
+ # Group the DataFrame by the 'Subreddit' column
17
+ grouped_df = df.groupby('Subreddit')
18
+
19
+ for subreddit, group in grouped_df:
20
+ subreddit_data = {
21
+ "Subreddit": subreddit,
22
+ "Posts": []
23
+ }
24
+
25
+ # Dictionary to keep track of post titles and their corresponding post IDs
26
+ post_title_to_id = {}
27
+
28
+ for index, row in group.iterrows():
29
+ post_title = row['Post Title']
30
+ comment_body = row['Comment Body']
31
+ timestamp = row['Timestamp']
32
+ upvotes = row['Upvotes']
33
+ ID = row['ID']
34
+ author = row['Author']
35
+ replies = row['Number of Replies']
36
+
37
+ # Check if the post title already exists under the subreddit
38
+ if post_title in post_title_to_id:
39
+ post_id = post_title_to_id[post_title]
40
+ # Append comment to existing post
41
+ for post in subreddit_data["Posts"]:
42
+ if post['PostID'] == post_id:
43
+ post['Comments'].append({
44
+ "CommentID": ID,
45
+ "Author": author,
46
+ "CommentBody": comment_body,
47
+ "Timestamp": timestamp,
48
+ "Upvotes": upvotes,
49
+ "NumberofReplies": replies
50
+ })
51
+ break
52
+ else:
53
+ # If the post title does not exist, create a new entry
54
+ post_id = len(subreddit_data["Posts"]) + 1
55
+ post_title_to_id[post_title] = post_id
56
+ subreddit_data["Posts"].append({
57
+ "PostID": post_id,
58
+ "PostTitle": post_title,
59
+ "Comments": [{
60
+ "CommentID": ID,
61
+ "Author": author,
62
+ "CommentBody": comment_body,
63
+ "Timestamp": timestamp,
64
+ "Upvotes": upvotes,
65
+ "NumberofReplies": replies
66
+ }]
67
+ })
68
+
69
+ transformed_data.append(subreddit_data)
70
+
71
+ return transformed_data