Las discusiones de Reddit brindan opiniones sin filtrar de los usuarios sobre productos, marcas y servicios. Este tutorial crea un rastreador de sentimientos que busca en Reddit menciones de marca a través del punto final de Reddit de Scavio, extrae temas de discusión y rastrea el sentimiento a lo largo del tiempo. A diferencia de la API nativa de Reddit (que requiere OAuth y tiene límites de velocidad estrictos), la búsqueda de Reddit de Scavio devuelve resultados estructurados con una simple llamada a la API.
Requisitos previos
- Python 3.8+ instalado
- solicita biblioteca instalada
- Una clave API de Scavio de scavio.dev
- Nombres de marcas o productos para rastrear
Guia paso a paso
Paso 1: Busque en Reddit menciones de marca
Consulte el punto final de Reddit de Scavio para obtener menciones de su marca o producto.
import requests, os
H = {'x-api-key': os.environ['SCAVIO_API_KEY']}
def search_reddit(query: str) -> list:
resp = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
json={'platform': 'reddit', 'query': query}, timeout=10)
return resp.json().get('organic', [])Paso 2: Extraer señales de sentimiento
Analice los títulos y fragmentos de las publicaciones en busca de señales positivas, negativas y neutrales.
POSITIVE = ['love', 'great', 'best', 'amazing', 'recommend', 'switched to', 'works well']
NEGATIVE = ['hate', 'worst', 'terrible', 'broken', 'avoid', 'switched from', 'stopped using']
def classify_sentiment(text: str) -> str:
text_lower = text.lower()
pos = sum(1 for w in POSITIVE if w in text_lower)
neg = sum(1 for w in NEGATIVE if w in text_lower)
if pos > neg: return 'positive'
if neg > pos: return 'negative'
return 'neutral'
def analyze_mentions(results: list) -> dict:
sentiments = {'positive': [], 'negative': [], 'neutral': []}
for r in results:
text = f"{r.get('title', '')} {r.get('snippet', '')}"
sentiment = classify_sentiment(text)
sentiments[sentiment].append({'title': r.get('title', ''), 'url': r.get('link', '')})
return sentimentsPaso 3: Generar un resumen de sentimiento
Calcule los índices de sentimiento y resalte las discusiones notables.
def sentiment_summary(sentiments: dict) -> dict:
total = sum(len(v) for v in sentiments.values())
return {
'total_mentions': total,
'positive_pct': round(len(sentiments['positive']) / max(total, 1) * 100, 1),
'negative_pct': round(len(sentiments['negative']) / max(total, 1) * 100, 1),
'neutral_pct': round(len(sentiments['neutral']) / max(total, 1) * 100, 1),
'top_positive': sentiments['positive'][:3],
'top_negative': sentiments['negative'][:3],
}Paso 4: Ejecute y guarde informes diarios
Ejecute el rastreador diariamente y almacene los resultados para el análisis de tendencias.
import json, datetime
def daily_sentiment(brand: str):
results = search_reddit(brand)
sentiments = analyze_mentions(results)
summary = sentiment_summary(sentiments)
date = datetime.date.today().isoformat()
report = {'date': date, 'brand': brand, **summary}
with open(f'sentiment_{brand}_{date}.json', 'w') as f:
json.dump(report, f, indent=2)
print(f"{brand}: {report['positive_pct']}% positive, {report['negative_pct']}% negative ({report['total_mentions']} mentions)")
return report
daily_sentiment('YourBrand')Ejemplo en Python
import requests, os
H = {'x-api-key': os.environ['SCAVIO_API_KEY']}
def reddit_sentiment(brand):
data = requests.post('https://api.scavio.dev/api/v1/search', headers=H,
json={'platform': 'reddit', 'query': brand}, timeout=10).json()
results = data.get('organic', [])
print(f'{brand}: {len(results)} Reddit mentions found')
return resultsEjemplo en JavaScript
async function redditSentiment(brand) {
const data = await fetch('https://api.scavio.dev/api/v1/search', {
method: 'POST', headers: {'x-api-key': process.env.SCAVIO_API_KEY, 'Content-Type': 'application/json'},
body: JSON.stringify({platform: 'reddit', query: brand})
}).then(r => r.json());
return data.organic || [];
}Salida esperada
Daily Reddit sentiment reports with positive/negative/neutral breakdowns and notable discussion highlights.