Skip to content

Instantly share code, notes, and snippets.

@kennethreitz
Last active November 8, 2023 22:11
Show Gist options
  • Save kennethreitz/4a27ce871d0c2587ebe2c4fda9d9326b to your computer and use it in GitHub Desktop.
Save kennethreitz/4a27ce871d0c2587ebe2c4fda9d9326b to your computer and use it in GitHub Desktop.
something I threw together for tracking sentiment of keywords for a company, with the help of ai
import os
import marvin
from serpapi import Client as SerpApi
serpapi = SerpApi(api_key=os.environ['SERPAPI_API_KEY'])
@marvin.ai_fn
def get_suggested_keywords(org_name: str) -> list[str]:
"""
Given an `org_name`, returns a list of suggested keywords to rank / track for SEO for that organization.
"""
@marvin.ai_fn
def sentiment_score(texts: list[str]) -> list[float]:
"""
Given a list of `texts`, returns a list of numbers between 1 (positive) and
-1 (negative) indicating their respective sentiment scores.
"""
def get_keyword_serp(keyword: str, with_snippet_sentiment=False) -> dict:
s = serpapi.search(
engine="google",
q=keyword
)
if with_snippet_sentiment:
return score_serp_descriptions(s)
return s.as_dict()
def score_serp_descriptions(serp: dict) -> dict:
scores = [sentiment_score([result['snippet']]) for result in serp['organic_results']]
for i, score in enumerate(scores):
serp['organic_results'][i]['sentiment-score'] = score
return serp
# ----
company = "Apple"
print(f"Company name: {company}.")
serp = get_keyword_serp(company)
suggested_keywords = get_suggested_keywords(company)
print(f"Suggested keywords to track: {suggested_keywords}")
for keyword in suggested_keywords:
print()
print(f"Getting SERP for {keyword} and scoring snippet sentiment.")
s = get_keyword_serp(keyword, with_snippet_sentiment=True)
for result in s['organic_results']:
print(f"{result['position']}: {result['title']}: {result['sentiment-score']}")
@kennethreitz
Copy link
Author

just a neat idea. not too much to see here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment