SEO Keywords Generator

python 2 views 2 hours, 19 minutes ago Public
Raw Download
python 6552 characters
#!/usr/bin/env python3
"""
SEO Keyword Generator and Analyzer
Generates keyword variations and analyzes keyword density
"""

import re
from collections import Counter
from itertools import combinations

def generate_keyword_variations(base_keyword, modifiers=None):
    """
    Generate keyword variations with common modifiers
    
    Args:
        base_keyword (str): The main keyword
        modifiers (list): Optional list of modifiers
    
    Returns:
        list: List of keyword variations
    """
    if modifiers is None:
        modifiers = [
            'best', 'top', 'cheap', 'affordable', 'premium',
            'professional', 'online', 'free', 'how to',
            'guide', 'tutorial', 'tips', 'review', 'vs',
            '2024', '2025', 'near me', 'for beginners'
        ]
    
    variations = [base_keyword]
    
    # Add modifier + keyword
    for modifier in modifiers:
        variations.append(f"{modifier} {base_keyword}")
        variations.append(f"{base_keyword} {modifier}")
    
    # Add question formats
    question_words = ['what', 'why', 'how', 'when', 'where', 'who']
    for word in question_words:
        variations.append(f"{word} is {base_keyword}")
        variations.append(f"{word} to {base_keyword}")
    
    return variations

def generate_long_tail_keywords(base_keyword, topics=None):
    """
    Generate long-tail keyword variations
    """
    if topics is None:
        topics = ['guide', 'tutorial', 'tips', 'tricks', 'strategies']
    
    long_tail = []
    
    templates = [
        f"best {base_keyword} for beginners",
        f"how to choose {base_keyword}",
        f"{base_keyword} vs alternatives",
        f"top 10 {base_keyword} tips",
        f"{base_keyword} complete guide",
        f"affordable {base_keyword} options",
        f"{base_keyword} for small business",
        f"professional {base_keyword} services",
        f"{base_keyword} pricing comparison",
        f"free {base_keyword} tools"
    ]
    
    long_tail.extend(templates)
    
    return long_tail

def analyze_keyword_density(text, top_n=20):
    """
    Analyze keyword density in text
    
    Args:
        text (str): The text to analyze
        top_n (int): Number of top keywords to return
    
    Returns:
        dict: Keyword density analysis
    """
    # Clean and tokenize
    text = text.lower()
    words = re.findall(r'[a-z]{3,}', text)
    
    # Common stop words to exclude
    stop_words = {
        'the', 'and', 'for', 'are', 'but', 'not', 'you', 'all',
        'can', 'her', 'was', 'one', 'our', 'out', 'day', 'get',
        'has', 'him', 'his', 'how', 'man', 'new', 'now', 'old',
        'see', 'two', 'way', 'who', 'boy', 'did', 'its', 'let',
        'put', 'say', 'she', 'too', 'use', 'that', 'this', 'will',
        'with', 'have', 'from', 'they', 'been', 'were', 'what'
    }
    
    # Filter stop words
    filtered_words = [w for w in words if w not in stop_words]
    
    # Count occurrences
    word_counts = Counter(filtered_words)
    total_words = len(filtered_words)
    
    # Calculate density
    keyword_density = {}
    for word, count in word_counts.most_common(top_n):
        density = (count / total_words) * 100
        keyword_density[word] = {
            'count': count,
            'density': round(density, 2)
        }
    
    # Analyze 2-word phrases
    bigrams = [' '.join(filtered_words[i:i+2]) 
               for i in range(len(filtered_words)-1)]
    bigram_counts = Counter(bigrams)
    
    return {
        'total_words': total_words,
        'unique_words': len(word_counts),
        'top_keywords': keyword_density,
        'top_phrases': dict(bigram_counts.most_common(10))
    }

def generate_meta_description(keyword, max_length=160):
    """
    Generate SEO-friendly meta description templates
    """
    templates = [
        f"Discover the best {keyword} solutions. Expert tips, guides, and reviews to help you choose the right {keyword} for your needs.",
        f"Looking for {keyword}? Get comprehensive guides, tutorials, and expert advice on {keyword}. Start here!",
        f"Everything you need to know about {keyword}. From beginner guides to advanced tips. Learn more now!",
        f"Find top-rated {keyword} options. Compare features, prices, and reviews. Make an informed decision today!",
        f"Master {keyword} with our complete guide. Tips, tricks, and best practices for success. Get started now!"
    ]
    
    return [desc[:max_length] for desc in templates]

def generate_title_tags(keyword, max_length=60):
    """
    Generate SEO-friendly title tag templates
    """
    templates = [
        f"Best {keyword} - Complete Guide 2024",
        f"{keyword}: Tips, Tricks & Expert Advice",
        f"Top {keyword} Solutions | Expert Reviews",
        f"How to Choose {keyword} - Ultimate Guide",
        f"{keyword} 101: Everything You Need to Know",
        f"Professional {keyword} Services & Solutions",
        f"{keyword} Comparison & Buying Guide"
    ]
    
    return [title[:max_length] for title in templates]

if __name__ == '__main__':
    # Example usage
    keyword = "web hosting"
    
    print("=== SEO Keyword Generator ===\n")
    
    print(f"Base Keyword: {keyword}\n")
    
    print("Keyword Variations:")
    variations = generate_keyword_variations(keyword)
    for i, var in enumerate(variations[:15], 1):
        print(f"  {i}. {var}")
    
    print("\nLong-tail Keywords:")
    long_tail = generate_long_tail_keywords(keyword)
    for i, lt in enumerate(long_tail, 1):
        print(f"  {i}. {lt}")
    
    print("\nTitle Tag Ideas:")
    titles = generate_title_tags(keyword)
    for i, title in enumerate(titles, 1):
        print(f"  {i}. {title}")
    
    print("\nMeta Description Ideas:")
    descriptions = generate_meta_description(keyword)
    for i, desc in enumerate(descriptions[:3], 1):
        print(f"  {i}. {desc}")
    
    # Example text analysis
    sample_text = """
    Web hosting is essential for any website. The best web hosting 
    services offer reliable uptime and fast performance. When choosing 
    web hosting, consider factors like speed, security, and support.
    """
    
    print("\nKeyword Density Analysis:")
    analysis = analyze_keyword_density(sample_text)
    print(f"Total words: {analysis['total_words']}")
    print(f"Unique words: {analysis['unique_words']}")
    print("\nTop keywords:")
    for word, data in list(analysis['top_keywords'].items())[:5]:
        print(f"  {word}: {data['count']} times ({data['density']}%)")