shuffle

code Python verified Бесплатная загрузка devices Кроссплатформенный

code Предпросмотр кода

Python
#!/usr/bin/env python3
"""
Spin Text Generator
Generate A/B testing variations from spin syntax templates
"""
import random
import re

def spin_text(text):
    """Replace {option1|option2} patterns with random choice"""
    pattern = r'\{([^}]+)\}'

    def replace(match):
        options = match.group(1).split('|')
        return random.choice(options)

    return re.sub(pattern, replace, text)

def generate_variations(template, count=5):
    """Generate multiple unique variations"""
    variations = set()
    attempts = 0
    max_attempts = count * 10

    while len(variations) < count and attempts < max_attempts:
        variation = spin_text(template)
        variations.add(variation)
        attempts += 1

    return list(variations)

def count_possible_variations(template):
    """Count total possible unique variations"""
    pattern = r'\{([^}]+)\}'
    matches = re.findall(pattern, template)

    total = 1
    for match in matches:
        options = match.split('|')
        total *= len(options)

    return total

def validate_template(template):
    """Validate spin syntax is correct"""
    open_braces = template.count('{')
    close_braces = template.count('}')

    if open_braces != close_braces:
        return False, "Mismatched braces"

    # Check for empty options
    if '||' in template or '{|' in template or '|}' in template:
        return False, "Empty option found"

    return True, "Valid template"

if __name__ == '__main__':
    template = '''Hi {there|John|friend},

I wanted to {reach out|connect|touch base} about {our product|our service|working together}.

{Would you be free|Could we schedule|Do you have time} for a {quick call|brief chat|15-minute meeting}?

{Best|Regards|Thanks},
{Alex|The Team}'''

    print(f"Possible variations: {count_possible_variations(template)}")
    print("\nGenerated variations:")
    for i, var in enumerate(generate_variations(template, 3), 1):
        print(f"\n--- Version {i} ---")
        print(var)

info Об инструменте

Генератор спин-текста создаёт множество вариаций писем из одного шаблона, используя спин-синтаксис. Идеально для A/B тестирования и избежания обнаружения дублей.

Спин-синтаксис

  • {option1|option2|option3} - Случайный выбор
  • Вложение в любом месте текста
  • Множество спин-блоков на шаблон

Ключевые особенности

  • Множество вариаций - Генерация неограниченного числа уникальных версий
  • Счётчик вариаций - Показывает общее число возможных комбинаций
  • Validation - Проверка синтаксиса перед обработкой
  • Дедупликация - Обеспечивает уникальные результаты
  • Bulk Export - Генерация CSV с вариациями

Применение

  • A/B тестирование - Тестирование разных тем и призывов к действию
  • Антиспам - Уникальный контент обходит фильтры
  • Персонализация - Динамические вариации приветствий

Требования

  • Python 3.7+
  • Без внешних зависимостей

Примечание: Используйте ответственно. Спин-текст должен улучшать настоящую коммуникацию, а не маскировать спам.

download Скачать скрипт

Нужна полная автоматизация?

Попробуйте Postigo для автоматизированных email-кампаний с AI-персонализацией

rocket_launch Start Free Trial