Advertisement
jarekmor

YoutubeCommentsAnalyzer

Nov 8th, 2024
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.86 KB | None | 0 0
  1. import json
  2. import requests
  3.  
  4. def get_all_comments(video_id, api_key):
  5.     comments = []
  6.     url = f"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId={video_id}&key={api_key}&maxResults=100"
  7.     while url:
  8.         response = requests.get(url)
  9.         data = response.json()
  10.         for item in data["items"]:
  11.             comment = {
  12.                 "text": item["snippet"]["topLevelComment"]["snippet"]["textDisplay"],
  13.                 "likeCount": item["snippet"]["topLevelComment"]["snippet"]["likeCount"],
  14.                 "publishedAt": item["snippet"]["topLevelComment"]["snippet"][
  15.                     "publishedAt"
  16.                 ],
  17.                 "authorDisplayName": item["snippet"]["topLevelComment"]["snippet"][
  18.                     "authorDisplayName"
  19.                 ],
  20.                 "replies": [],
  21.             }
  22.             if "replies" in item:
  23.                 for reply in item["replies"]["comments"]:
  24.                     comment["replies"].append(
  25.                         {
  26.                             "text": reply["snippet"]["textDisplay"],
  27.                             "likeCount": reply["snippet"]["likeCount"],
  28.                             "publishedAt": reply["snippet"]["publishedAt"],
  29.                             "authorDisplayName": reply["snippet"]["authorDisplayName"],
  30.                         }
  31.                     )
  32.             comments.append(comment)
  33.         url = data.get("nextPageToken")
  34.         if url:
  35.             url = f"https://www.googleapis.com/youtube/v3/commentThreads?part=snippet&videoId={video_id}&key={api_key}&maxResults=100&pageToken={url}"
  36.     return comments
  37.  
  38. def save_comments_to_file(comments, filename="comments.json"):
  39.     with open(filename, "w", encoding="utf-8") as f:
  40.         json.dump(comments, f, ensure_ascii=False, indent=4)
  41.     print(f"Comments have been saved to {filename}")
  42.  
  43. def generate_text_file(comments, filename="comments.txt"):
  44.     with open(filename, "w", encoding="utf-8") as f:
  45.         for comment in comments:
  46.             f.write(f"Comment: {comment['text']}\n")
  47.             f.write(f"Likes: {comment['likeCount']}\n")
  48.             f.write(f"Date: {comment['publishedAt']}\n")
  49.             f.write(f"Author: {comment['authorDisplayName']}\n")
  50.             if comment["replies"]:
  51.                 f.write(f"Replies ({len(comment['replies'])}):\n")
  52.                 for reply in comment["replies"]:
  53.                     f.write(f"- Reply: {reply['text']}\n")
  54.             f.write("\n---\n\n")
  55.     print(f"Comments have been saved to {filename}")
  56.  
  57. # Example usage
  58. if __name__ == "__main__":
  59.     # Replace these with your actual values
  60.     VIDEO_ID = "YouTube movie ID"                       # ID filmu np. X-i1oBrh2LI
  61.     API_KEY = "YouTube_API_KEY"                         # <-------- miejsce na YouTube API KEY
  62.  
  63.     # Get all comments
  64.     comments = get_all_comments(VIDEO_ID, API_KEY)
  65.  
  66.     # Save to file
  67.     save_comments_to_file(comments)
  68.  
  69.     # Generate text file
  70.     generate_text_file(comments)
  71.  
  72.     # Print summary
  73.     print(f"Total comments fetched: {len(comments)}")
  74.     total_replies = sum(len(comment["replies"]) for comment in comments)
  75.     print(f"Total replies fetched: {total_replies}")
  76.  
  77. """
  78. Example prompt for ChatGPT:
  79.  
  80. You are a data analyst specializing in social media content and sentiment analysis. I will provide you with YouTube comments data. Please analyze these comments and provide comprehensive insights in the following areas:
  81. 1. Sentiment and Emotional Analysis
  82.  
  83. Analyze the overall sentiment of comments (positive, negative, neutral)
  84. Identify emotional patterns and themes
  85. Point out particularly notable emotional responses
  86. Highlight any interesting patterns in how viewers express their feelings
  87.  
  88. 2. Content and Topics Analysis
  89.  
  90. Identify main discussion themes and topics
  91. Find recurring subjects or patterns in discussions
  92. Note any interesting debates or disagreements
  93. Analyze references to external topics, events, or other content
  94. Identify inside jokes or community-specific references
  95.  
  96. 3. Engagement Patterns
  97.  
  98. Analyze patterns in likes and replies
  99. Identify what types of comments generate the most engagement
  100. Look for conversation chains and discussion patterns
  101. Note any viral or highly-referenced comments
  102. Examine user interaction patterns
  103.  
  104. 4. Community Behavior
  105.  
  106. Identify community-specific language or jargon
  107. Analyze how users interact with each other
  108. Note any community roles or recurring user types
  109. Identify community consensus or disagreements
  110. Examine response patterns to different topics
  111.  
  112. 5. Technical Language Analysis
  113.  
  114. Identify commonly used terms and phrases
  115. Analyze language complexity and style
  116. Note any multilingual patterns or language mixing
  117. Identify unique expressions or terminology
  118.  
  119. 6. Temporal Analysis
  120.  
  121. Note any changes in comment patterns over time
  122. Identify peak engagement periods
  123. Analyze how discussions evolved
  124. Note any event-related commenting patterns
  125.  
  126. Additional Instructions:
  127.  
  128. Support your analysis with specific examples from the comments
  129. Provide numerical data when relevant
  130. Highlight unexpected or particularly interesting findings
  131. Note any limitations in your analysis
  132. Suggest potential interpretations of patterns you identify
  133. If relevant, compare patterns to typical social media behavior
  134.  
  135. Please structure your response with clear headings and bullet points for readability. Prioritize insights that would be most valuable for understanding audience engagement and community dynamics.
  136. For each observation, try to provide:
  137.  
  138. The specific finding
  139. Supporting evidence/examples
  140. Possible interpretation
  141. Relevance or implications
  142.  
  143. Note: If you notice any other significant patterns or insights not covered by these categories, please include them in your analysis.
  144. End your analysis with a summary of the most significant findings and any recommendations for future analysis or engagement strategies.
  145.  
  146. Answer in Polish language:
  147.  
  148. """
  149.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement