from nltk.corpus import wordnet
from nltk.tokenize import word_tokenize
import random

def get_synonym(word):
    synonyms = wordnet.synsets(word)
    if not synonyms:
        return word
    lemmas = set()
    for syn in synonyms:
        for lemma in syn.lemmas():
            if lemma.name().lower() != word.lower():
                lemmas.add(lemma.name().replace('_', ' '))
    return random.choice(list(lemmas)) if lemmas else word

def synonym_replace(sentence, ratio=0.3):
    words = word_tokenize(sentence)
    new_words = []
    for word in words:
        if word.isalpha() and random.random() < ratio:
            new_word = get_synonym(word)
            new_words.append(new_word)
        else:
            new_words.append(word)
    return ' '.join(new_words)

# 示例测试
text = "The quick brown fox jumps over the lazy dog."
augmented = synonym_replace(text, ratio=0.5)
print("原文：", text)
print("替换后：", augmented)
