How to Do Sentiment Analysis on YouTube Comments

2026-12-02来源 dev.toEnglish

I run Serpent, the API used in the examples below.

To measure sentiment in YouTube comments fairly, read them newest-first, slice them by the age YouTube shows, and weight likes with care. The top ranking changes between calls and can favour old, heavily liked comments. Treat the result as a sample of public text on videos you chose, never a verdict on the audience.

Short answer: To compare a creator's videos, read the newest few hundred comments of each with sort=newest and compare equal-size windows. For a before-and-after around a launch, page newest-first until the labels pass your cutoff, and accept week-sized resolution. For a quick look at what is prominent today, use sort=top and call it a snapshot.

A comment section is where an audience talks back, which makes it tempting raw material for questions like how viewers took a product launch or which of a creator's videos landed best. The data is easy to fetch and easy to misread.

The usual tutorials fetch comments, run a polarity score and draw a pie chart. I opened four of them for this post on 24 November 2026, and none slices by time, none says which sort it fetched, and none mentions data protection. This guide covers those three. For the request code in Python and Node, next to YouTube's official route, see how to get YouTube comments in Python and Node.

Every number below about my API's output comes from answers it returned on 29 November 2026, saved before launch: two sort=top pages (trimmed to 2 and 1 of their 20 comments), one newest-first page of 20 comments and two pages of replies to one comment. The code contains no sentiment model on purpose: I did not run one, so I will not quote an accuracy figure for any model. Serpent is not affiliated with YouTube or Google.

What can comment sentiment actually tell you?

A direction, for the people who comment, on the videos you chose. It is not the mood of every viewer, because most viewers never write a comment and those who do lean toward strong feelings. That is still enough for comparisons, as long as you compare like with like.

Three questions suit it well:

  • How did the audience react across a creator's videos? Same window, same method, one number per video.
  • Did reaction shift around a launch or an update? Two slices of the same video, before and after.
  • What are people saying in the newest comments? A rolling view that you can run again next week.

It cannot tell you why people feel what they feel, and it says nothing about people who stayed silent. Write that next to any chart you publish.

Which sort should you read, top or newest?

Read newest for anything you want to run again, and top only for a labelled snapshot. sort=top is YouTube's own ranking, and it changes between calls. sort=newest walks the list in time order, one page after another.

In a check I ran on 24 November 2026, two videos were each fetched twice, ten minutes apart. On page one 17 and 16 of the first 20 top comments repeated, and on page two 15 and 8 of 20 did. I did not repeat the check for this post. A sample you cannot draw twice is a poor base for a trend line.

The answers saved on 29 November also show what each sort puts in front of you on a popular video. The three saved top comments are all seven years old, while the 20 saved newest comments are between 7 minutes and 3 hours old. All three top comments are older than a year; none of the 20 newest is.

Your question Sort Why
What is prominent on this video today? top YouTube's ranking, so a snapshot you label as one
How did reaction change over weeks? newest Time order, so a cursor walk gives slices
Which video of this creator got the warmest reception? newest Equal-size windows you can run again
Which comments will people see first? top That is what the ranking is for

What does one call give you?

One call returns one page of top-level comments, not one comment: each of the three comment pages saved for this post held 20. Send your key in the X-API-Key header and a video id or link as video. The first page of a walk also carries total_comments (2,462,804 on the saved top page, and null on its second page), and each page carries a next_cursor for the page after it. The docs list every field.

This is the first comment of the saved newest-first answer for a popular video. The text, handle and ids are invented; the age, likes and other values are as saved:

{ "comment_id": "c04…", "text": "Playing this while I tidy my desk", "author": "@viewer4", "author_channel_id": "UC…", "published": "7 minutes ago", "is_edited": false, "likes": 0, "like_text": "", "reply_count": 0, "replies_cursor": null, "is_pinned": false, "is_hearted": false, "is_creator": false, "is_verified": false } 

Most fields are what you would expect. A few shape the analysis:

Field What it is How to use it
text The comment as written The only field you need to score
published Relative words, such as "3 weeks ago" Slice by age; no exact timestamp exists
is_edited Whether the comment is marked "(edited)" Keep it if edits matter to you; otherwise ignore it when scoring
likes, like_text The count as shown, and its original wording such as "128K" Rounded above 999, so treat it as approximate
reply_count, replies_cursor How many replies, and the handle to fetch them Thread-level analysis
is_creator, is_pinned Whether the channel owner wrote or pinned it Drop these before scoring audience sentiment
author, author_channel_id Who wrote it Drop them; see the data-protection section

Know how the values arrive. Likes are rounded above 999, published is relative to the moment of your call, and the depth of a walk is not something I give a number for. Treat each walk as a sample, not as the full record of a video.

How do you slice by time without exact dates?

Page newest-first and bucket each comment by the age in its published text. Because the list is in time order, the first pages hold the newest comments and each later page reaches further back. You stop when the labels pass your cutoff.

Store the time of your call with every page. A label such as "1 day ago" is relative to that moment, so tomorrow's walk of the same video labels the same comment differently. With the retrieval time saved, you can turn a label into an approximate date later.

Here is a small module that walks pages, keeps only the fields the analysis needs, turns the age words into rough days and counts comments per slice. It is example code for the request side, and the printed output below is the same file run over a saved answer, with only the network call returning that answer.

import re import time import requests API_KEY = "sk_live_your_api_key" URL = "https://apiserpent.com/api/social/youtube/comments" REPLIES_URL = URL + "/replies" KEEP = ("comment_id", "text", "published", "likes", "reply_count", "replies_cursor") UNIT_DAYS = {"second": 1 / 86400, "minute": 1 / 1440, "hour": 1 / 24, "day": 1, "week": 7, "month": 30, "year": 365} def age_days(published): """The age words ('3 weeks ago') as a rough number of days, or None.""" m = re.match(r"\s*(\d+)\s+(second|minute|hour|day|week|month|year)s?\s+ago", published or "") return int(m.group(1)) * UNIT_DAYS[m.group(2)] if m else None def get(url, **params): r = requests.get(url, params=params, headers={"X-API-Key": API_KEY}, timeout=60) r.raise_for_status() return r.json() def newest_pages(video, pages=5, cutoff_days=None): """Walk the newest-first list one page at a time (20 comments in the saved answers). Stops early once a page reaches comments older than cutoff_days.""" cursor = None for _ in range(pages): params = {"video": video, "sort": "newest"} if cursor: params["cursor"] = cursor page = get(URL, **params) yield page cursor = page.get("next_cursor") ages = [age_days(c["published"]) for c in page["comments"] if not c["is_pinned"]] if not cursor or (cutoff_days and ages and None not in ages and max(ages) > cutoff_days): break time.sleep(1) def slim(comment): """Keep only what the analysis needs: no author name, no channel id.""" return {k: comment.get(k) for k in KEEP} def slice_by_age(comments, edges=(1, 7, 30)): labels = ["under 1 day", "1 to 7 days", "7 to 30 days", "30 days or more"] buckets = {label: [] for label in labels} for c in comments: d = age_days(c["published"]) if d is None: continue i = next((n for n, edge in enumerate(edges) if d < edge), len(edges)) buckets[labels[i]].append(c) return buckets def replies_page(video, cursor): """One call to the replies endpoint: slim replies plus the cursor for the next call. The size of a page varies (9 replies on the first call and 45 on the second in the saved answers).""" page = get(REPLIES_URL, video=video, cursor=cursor) return [slim(r) for r in page["replies"]], page.get("next_cursor") if __name__ == "__main__": comments = [] for page in newest_pages("dQw4w9WgXcQ", pages=1, cutoff_days=30): # one page here; raise pages for a real walk comments += [slim(c) for c in page["comments"] if not (c["is_creator"] or c["is_pinned"])] for label, rows in slice_by_age(comments).items(): print(f"{label:16} {len(rows):3} comments") 

Its output over the saved newest-first answer, which holds 20 comments:

under 1 day 20 comments 1 to 7 days 0 comments 7 to 30 days 0 comments 30 days or more 0 comments 

The saved comments are labelled from "7 minutes ago" to "3 hours ago", so all 20 land under a day.

That is the point to take away: on a video this busy, one page reaches back only a few hours, so a slice a week wide takes many pages. I saved one page, so I give no page count for a week. The loop in __main__ asks for one page here; raise pages for a real walk. To score each slice, add one function that takes a comment's text and returns a number from whichever model you trust, then average it per bucket.

Mind the resolution. The further back a comment is, the coarser the wording: a label such as "3 weeks ago" tells you the week, not the day. Put slice edges on whole units (a day, a week, a month) and do not claim a launch-day boundary the labels cannot show.

How do you compare videos or a launch fairly?

Compare equal windows, and say what the window is. The usual mistake is comparing the newest 200 comments of a video that gets hundreds a day with the newest 200 of an older video, where those 200 span a year. They are different samples even though the code is identical.

For a creator's videos, take the same count from each with sort=newest, remove the creator's own comments with is_creator, drop duplicates by comment_id, and score every video with the same model. Report the count next to each score. A score from 40 comments and a score from 400 deserve different trust.

For a before-and-after, cut one walk into two slices at your launch date. Remember that a launch changes who comments: a new audience arrives, so a shift can reflect different people, not changed minds. Small slices also swing: with 30 comments in a slice, three comments change a share by 10 percentage points. Read a handful of comments in each slice yourself, and if your reading and the score disagree, trust your reading.

How should likes count in a score?

Count each comment once unless you have a reason not to. Like-weighting sounds sensible, but a handful of comments can hold almost all the weight. In the saved replies to one top comment, the first call returned 9 replies, and those 9 hold 98.7% of the 21,431 likes across the 54 replies saved (9 from the first call and 45 from the second). The most-liked reply alone holds 30.3%.

Top-level comments pull the same way: of the three saved top comments, the one with 128K likes holds 44.8% of their 286,000 likes. When a few comments hold most of the likes, a like-weighted average is mostly their sentiment. Likes do not set the top order by themselves either: the second saved comment on page one has 73K likes and the first saved comment on page two has 85K. One thread is a tiny sample, so read these shares as arithmetic, not as a finding about YouTube.

Newest-first walks make this nearly moot. Of the 20 saved newest comments, 18 have 0 likes and 2 have 1, and all 20 have 0 replies, which is normal for comments posted minutes or hours earlier. A like-weighted score of a fresh slice would have nothing to weigh.

If you do want weight, cap it or take a logarithm of the likes so one viral comment cannot dominate, and publish the unweighted score next to it. Choose the rule before you look at the result.

Do replies change the picture?

Often, because a reply can confirm or undercut the comment above it. Fetch them with replies_page in the module above, which sends a comment's replies_cursor to /api/social/youtube/comments/replies and returns the replies with the cursor for the next call. The size of a page varies. The first saved top comment has 702 replies: the first call returned 9 (1.3% of the thread) and the second 45, so two calls reached 54 replies, 7.7%, and there was still a next_cursor.

Among the 54 saved replies, the first call held the most-liked ones, so they are not a random sample of the thread. Decide how deep you need to go before you build the loop.

YouTube's own Data API is the other route for comments. Its commentThreads.list method costs 1 quota unit per call and returns up to 100 comments, against a default quota of 10,000 units per day, both read on Google's quota page and in the commentThreads.list docs on 24 November 2026. It needs a Google API key and project, and it is free. If you do not mind the Cloud project, it is a fair choice here; the how-to post sets both routes side by side.

How do you keep it on the right side of data-protection rules?

Treat comments as public text written by real people, analyse them in aggregate, and keep only what the analysis needs. You are responsible for using the data lawfully, including under data-protection law. I am not a lawyer, and what is lawful depends on where you are, why you analyse and what you store.

The reason for care is simple: a handle, a channel id and a sentence together can identify a person, even though the post is public. Comments can also reveal health, politics or other sensitive matters that the writer never meant for a dataset. Sentiment work on a launch needs none of that.

Habits that keep the analysis in aggregate:

  • Drop author and author_channel_id at the door, as the slim function above does.
  • Never look up an author's other comments or build a profile of one person across videos.
  • Store scores and counts, and delete raw text once you have scored it, unless you have a reason to keep it.
  • Do not republish raw comments with names attached; quote sparingly and without the handle.

Regulators describe the same habits. The European Data Protection Board's Guidelines 03/2026, adopted on 7 July 2026 as a draft for public consultation, say the GDPR applies when personal data from public web sources is collected, and list minimisation measures such as precise collection criteria and pseudonymisation. The UK ICO's page on the lawful basis says, in its call for evidence, that legitimate interests was realistically the only lawful basis developers could explore and needs a three-part test. Both are about training generative AI, which is a different use from yours, so take the questions they ask, not their conclusions.

Which setup should you pick?

  • Comparing a creator's recent videos: sort=newest, the same count from each (for example 200), creator comments removed, one model, counts reported next to each score.
  • Before and after a launch: one newest-first walk with a cutoff past the launch, slices on whole weeks, equal minimum size per slice, and a note that the audience may have changed.
  • A weekly pulse on one video: the newest 100 to 200 comments each Monday, stored as scores and counts only.
  • A one-off look at what stands out: sort=top, labelled as a snapshot that can differ tomorrow.
  • Thread-level reading of a few big discussions: fetch the replies for those comments only, after you have scored the top level.

To try the shape of a response first, use the playground on the Serpent site; a new key comes with 10 free calls. The YouTube Comments API page has the field list, and YouTube transcripts for AI and RAG pipelines covers what was said in the video itself.

How I checked this, and what I could not verify

The Python module above was run unchanged against the saved answers, with only the network call returning them. The saved answers were returned by my API on 29 November 2026. They hold two sort=top pages (trimmed to 2 and 1 of the 20 comments each call returned), one newest-sort page of 20, the first two replies calls for one comment (9 and 45 replies) and three empty answers, with comment text, handles and ids replaced by invented ones, so every number computed from them describes those few comments only. I also opened four existing tutorials on 24 November 2026 to see what they cover, the two Google documentation pages for the official route, the EDPB guidelines and the ICO page.

  • I made no live call for this post, so the paging loop beyond one page is example code, and replies_page ran only over the two saved replies answers.
  • The top-sort stability figures (17 and 16 of 20 on page one, 15 and 8 of 20 on page two) come from a check of mine on 24 November 2026, and I did not repeat them.
  • The saved top-sort pages are trimmed, so the top-level like shares describe three comments, and the reply like shares describe one thread.
  • I did not run a sentiment model, so the post gives no accuracy figure for any model and the code has no scoring function.
  • Nothing here measures how many comments a given video lets you page through; the depth varies and I give no number.
  • The EDPB text is a draft adopted for consultation about generative-AI scraping, and the ICO page shows no date. Neither is advice for your case.

Originally published on apiserpent.com. The original also has the figures and a longer FAQ. See also how to get YouTube comments in Python and Node.

原文:https://www.a8q9.cn/en/article/how-to-do-sentiment-analysis-on-youtube-comments-d58d8d.html

相关文章