惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Engineering at Meta
Engineering at Meta
T
Threatpost
P
Palo Alto Networks Blog
NISL@THU
NISL@THU
O
OpenAI News
Project Zero
Project Zero
G
GRAHAM CLULEY
P
Privacy International News Feed
A
Arctic Wolf
Microsoft Azure Blog
Microsoft Azure Blog
H
Help Net Security
M
MIT News - Artificial intelligence
T
Threat Research - Cisco Blogs
S
Security @ Cisco Blogs
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
D
Docker
aimingoo的专栏
aimingoo的专栏
博客园 - 【当耐特】
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
雷峰网
雷峰网
W
WeLiveSecurity
P
Proofpoint News Feed
腾讯CDC
Cloudbric
Cloudbric
S
Secure Thoughts
C
Check Point Blog
博客园 - Franky
T
The Exploit Database - CXSecurity.com
T
Troy Hunt's Blog
GbyAI
GbyAI
Security Archives - TechRepublic
Security Archives - TechRepublic
Application and Cybersecurity Blog
Application and Cybersecurity Blog
月光博客
月光博客
C
Cyber Attacks, Cyber Crime and Cyber Security
I
Intezer
TaoSecurity Blog
TaoSecurity Blog
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
F
Fortinet All Blogs
博客园 - 叶小钗
C
CXSECURITY Database RSS Feed - CXSecurity.com
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Recorded Future
Recorded Future
C
Cisco Blogs
博客园 - 司徒正美
Stack Overflow Blog
Stack Overflow Blog
Y
Y Combinator Blog
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
What Reddit Can Teach Us About Women’s Watch Preferences (Python + NLP Project)
elizabeththo · 2026-05-08 · via DEV Community

Most “what watch should I buy?” discussions online skew heavily male. A friend wanted to launch a women’s watch, so I helped with a small data analysis.

In this post I’ll walk through a small but complete Python pipeline I built:

  • Scrape relevant posts and comments from Reddit with no API keys
  • Filter out irrelevant posts (e.g. men asking for themselves)
  • Run NLP analysis: sentiment, brands, features, prices, keywords, clustering, topic modeling
  • Generate visualizations and CSVs you can explore further

Everything here is powered by standard Python libraries: requests, pandas, nltk, scikit‑learn, and wordcloud.

1. Collecting Reddit data without API keys

We didn’t use the official Reddit API; instead we hit the public JSON endpoints directly using requests.

At the top of reddit_json_scraper.py we define search URLs across multiple subreddits:

Each URL returns a JSON blob; we wrap that in a helper:

Reddit’s listing JSON has a fairly nested structure, so we created extract_post_data to normalize it into a flat dictionary with the fields we actually care about (ID, subreddit, title, body, score, comment count, timestamps, etc.):

def extract_post_data(post_json):
    """
    Extract relevant information from a Reddit post JSON
    """
    try:
        data = post_json['data']

        return {
            'post_id': data.get('id', ''),
            'subreddit': data.get('subreddit', ''),
            'title': data.get('title', ''),
            'text': data.get('selftext', ''),
            'author': data.get('author', ''),
            'score': data.get('score', 0),
            'upvote_ratio': data.get('upvote_ratio', 0),
            'num_comments': data.get('num_comments', 0),
            'created_utc': data.get('created_utc', 0),
            'created_date': datetime.fromtimestamp(data.get('created_utc', 0)).strftime('%Y-%m-%d %H:%M:%S'),
            'url': f"https://reddit.com{data.get('permalink', '')}",
            'post_url': data.get('url', ''),
            'is_video': data.get('is_video', False),
            'over_18': data.get('over_18', False)
        }

Enter fullscreen mode Exit fullscreen mode

The main collection loop simply iterates through all search URLs, fetches JSON, and appends normalized posts into a list:

We also fetch comments for the most “interesting” posts, sorted by engagement (score + num_comments), by hitting each post’s .json endpoint and walking the comment tree.

At the end of main() we save everything to CSV and run a quick text summary (brand and keyword counts, simple price stats).

2. Filtering: keeping posts that are really about women’s watches

Search results are noisy. Some posts mention “women” but are actually men asking for themselves.
filter_posts.py applies a simple but effective regex filter.We flag posts that contain phrases like “as a man” or “for men”:

…but we keep posts that clearly talk about buying for a woman, e.g. “gift for my wife”:

NON_FILTER_PATTERNS=r"(for|gift|buying|getting|choosing|help).*(mum|mom|mother|wife|girlfriend|partner|daughter|sister|woman|female|her|she)"

Enter fullscreen mode Exit fullscreen mode

filter_check combines title and text, applies these patterns, and filtered_posts_csv writes a cleaned filtered_posts.csv. This becomes the starting point for our analysis.

3. Analyzing the conversations with WatchDataAnalyzer

The main analysis lives in watch_analyzer.py as a single class:

  • Load the filtered posts and comments
  • Combine titles, bodies, and comment text into all_text
  • Set up NLTK and VADER sentiment

3.1. Light text cleaning

We remove URLs and normalize whitespace, then build a combined_text column per post:

3.2. Sentiment on posts and comments

Using VADER, we compute a compound score and label each post/comment as positive, neutral, or negative:

self.posts_df['sentiment_scores']=self.posts_df['combined_text'].apply(lambda x: self.sia.polarity_scores(x))
self.posts_df['sentiment_compound']=self.posts_df['sentiment_scores'].apply(lambda x: x['compound'])
self.posts_df['sentiment_label']=self.posts_df['sentiment_compound'].apply(
    lambda x: 'positive' if x>0.05 else ('negative' if x<-0.05 else 'neutral')
)

Enter fullscreen mode Exit fullscreen mode

We do the same for comments and then plot the distribution, saving sentiment_dist.png.

3.3. Brands, price ranges, and features

We look at three practical angles:

  • Brand mentions — a curated list from Titan and Seiko to Rolex and Omega, counted across all text.
def extract_brands(self):
    # Common watch brands
    brands = [
        'casio', 'seiko', 'citizen', 'timex', 'fossil', 'orient', 'tissot',
        'michael kors', 'daniel wellington', 'mvmt', 'skagen', 'swatch',
        'rolex', 'omega', 'cartier', 'tag heuer', 'breitling', 'patek philippe',
        'audemars piguet', 'vacheron constantin', 'baume mercier', 'longines',
        'hamilton', 'bulova', 'invicta', 'bering', 'titan', 'fastrack',
        'sonata', 'maxima', 'hmt', 'raymond weil', 'zenith', 'iwc'
    ]
    brand_mentions={}
    # ...

Enter fullscreen mode Exit fullscreen mode

  • Price — regexes to capture Indian price patterns with ₹/rs/inr or “rupees”, then bucketed into budget/mid‑range/premium/luxury ranges.
def extract_prices(self):
    # Patterns for price extraction
    patterns = [
        r'(?:₹|rs\.?|inr)\s*(\d+(?:,\d{3})*(?:\.\d+)?)',
        r'(\d+(?:,\d{3})*(?:\.\d+)?)\s*(?:₹|rs\.?|inr)',
        r'(\d+(?:,\d{3})*(?:\.\d+)?)\s*(?:rupees|rupee)',
    ]

    all_prices=[]

    for text in self.all_text:
        for pattern in patterns:
            matches=re.findall(pattern,str(text),re.IGNORECASE)
            for match in matches:
                price_str=match.replace(',','').replace('.','')
                all_prices.append(int(price_str))

    ranges = {
            'Budget (<₹5,000)': sum(1 for p in all_prices if p < 5000),
            'Mid-range (₹5,000-₹20,000)': sum(1 for p in all_prices if 5000 <= p < 20000),
            'Premium (₹20,000-₹1,00,000)': sum(1 for p in all_prices if 20000 <= p < 100000),
            'Luxury (>₹1,00,000)': sum(1 for p in all_prices if p >= 100000)
        }

Enter fullscreen mode Exit fullscreen mode

  • Features — categories like size, material, movement, style, strap, and “features” (water resistance, sapphire, chronograph, etc.), each with their own keyword list.

This gives a quick picture of which brands dominate, what price bands people discuss, and which attributes come up most.

3.4. Keywords, clusters, and topics

Using scikit‑learn:

TF‑IDF keywords — we build a TfidfVectorizer over combined_text
and save the top terms to keywords_tfidf.csv.

def extract_keywords(self):
    self.preprocess_all_text()

    vectorizer=TfidfVectorizer(
        max_features=80,
        stop_words='english',
        min_df=2
    )

    texts=self.posts_df['combined_text'].fillna('').tolist()
    X=vectorizer.fit_transform(texts)

    feature_names=vectorizer.get_feature_names_out()

    scores = X.mean(axis=0).A1

    # Create keyword dataframe
    keywords_df = pd.DataFrame({
        'keyword': feature_names,
        'tfidf_score': scores
    }).sort_values('tfidf_score', ascending=False)

Enter fullscreen mode Exit fullscreen mode

  • Clustering — we cluster posts into 5 groups using K‑Means over TF‑IDF vectors, then inspect top words per cluster.
def cluster_posts(self, n_clusters=5):
    """
    Cluster posts based on text similarity
    """
    # ...
    vectorizer = TfidfVectorizer(
        max_features=50,
        stop_words='english',
        min_df=2
    )

    texts = self.posts_df['combined_text'].fillna('').tolist()
    X = vectorizer.fit_transform(texts)

    # K-means clustering
    kmeans = KMeans(n_clusters=n_clusters, random_state=42, n_init=10)
    clusters = kmeans.fit_predict(X)

    self.posts_df['cluster'] = clusters

Enter fullscreen mode Exit fullscreen mode

  • Topic modeling — we run LDA/NMF over the same vectors to discover high‑level themes (“budget gifts”, “small wrists and office wear”, “sporty/outdoor”, etc.).
def topic_modeling(self, n_topics=5, method='lda'):
    """
    Perform topic modeling using LDA or NMF
    """
    # ...
    vectorizer = TfidfVectorizer(
        max_features=100,
        stop_words='english',
        ngram_range=(1, 2),
        min_df=2,
        max_df=0.95
    )
    # ...
    if method.lower() == 'lda':
        model = LatentDirichletAllocation(n_components=n_topics, random_state=42)
    else:  # NMF
        model = NMF(n_components=n_topics, random_state=42)
    # ...
    for idx, topic in enumerate(model.components_):
        top_words = [feature_names[i] for i in topic.argsort()[-10:][::-1]]
        print(f"\n   Topic {idx + 1}: {', '.join(top_words)}")

Enter fullscreen mode Exit fullscreen mode

4. Putting it all together

The generate_report() method runs the full pipeline:

  • Preprocess text
  • Run sentiment, brand/feature/price extraction
  • Compute keywords, clusters, and topics
  • Generate a word cloud and sentiment plot
  • Save everything to CSVs you can open in Excel or a notebook
def generate_report(self):

    # 1. Pre- processing the text 
    self.preprocess_all_text()

    # 2. Analyze sentiment
    sentiment_df=self.analyze_sentiment()

    # 3. Brands mentions
    brands=self.extract_brands()

    # 4. Features
    features = self.extract_features()

    # 5. Prices
    prices = self.extract_prices()

    # 6. Keywords
    keywords_df = self.extract_keywords()

    # 7. Clustering
    clusters = self.cluster_posts(n_clusters=5)

    # 8. Topic Modeling
    print("\n🔍 Running topic modeling (this may take a moment)...")
    topic_model, vectorizer = self.topic_modeling(n_topics=5, method='lda')

    # 9. Visualizations
    print("\n🎨 Creating visualizations...")
    self.create_wordcloud('wordcloud.png')
    self.plot_sentiment_distribution('sentiment_dist.png')

    # Save results ...

Enter fullscreen mode Exit fullscreen mode

It’s a compact example of how to go from raw Reddit JSON to structured insights about a very specific question: what are people really saying when they talk about women’s watches ?