Guest User

Untitled

a guest
Oct 19th, 2023
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. import json
  2. import csv
  3.  
  4. def extract_paid_messages(json_data):
  5. messages = []
  6.  
  7. # Check if 'replayChatItemAction' and 'actions' keys exist
  8. if 'replayChatItemAction' in json_data and 'actions' in json_data['replayChatItemAction']:
  9. for action in json_data['replayChatItemAction']['actions']:
  10. # Check if the required keys exist in the structure
  11. if 'addChatItemAction' in action and 'item' in action['addChatItemAction']:
  12. item = action['addChatItemAction']['item']
  13. if 'liveChatPaidMessageRenderer' in item:
  14. renderer = item['liveChatPaidMessageRenderer']
  15.  
  16. # Extracting the desired details
  17. name = renderer['authorName']['simpleText']
  18. message = None
  19. if ('message' in renderer and
  20. 'runs' in renderer['message'] and
  21. renderer['message']['runs'] and
  22. 'text' in renderer['message']['runs'][0]):
  23. message = renderer['message']['runs'][0]['text']
  24. amount = renderer['purchaseAmountText']['simpleText']
  25.  
  26. messages.append({
  27. 'name': name,
  28. 'message': message,
  29. 'amount': amount
  30. })
  31. return messages
  32.  
  33. # List to accumulate all results
  34. all_results = []
  35.  
  36. # Read from a file
  37. with open('#11.json', 'r', encoding='utf-8') as file:
  38. for line in file:
  39. data = json.loads(line)
  40. results = extract_paid_messages(data)
  41. all_results.extend(results) # Add the results to the accumulated list
  42.  
  43. # Now, write the accumulated results to the CSV file
  44. with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
  45. fieldnames = ['name', 'message', 'amount']
  46. writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter='|')
  47.  
  48. writer.writeheader()
  49. for msg in all_results:
  50. writer.writerow(msg)
Advertisement
Add Comment
Please, Sign In to add comment