import re from pypinyin import lazy_pinyin # 替换同音字 def replace_word(text, target_word): words = re.findall(r'\b\w+\b', text) for word in words: if is_same_pinyin(word, target_word): text = text.replace(word, target_word) return text # 判断拼音是否相同 def is_same_pinyin(word1, word2): return lazy_pinyin(word1) == lazy_pinyin(word2)