比一个简单的正则表达式更复杂,例如,
"Hi, how are you?" → "Hubi, hubow ubare yubou?"
简单的正则表达式将无法捕获
e未在中发音的正则表达式
are。
您需要一个提供发音词典的库,例如
nltk.corpus.cmudict:
from nltk.corpus import cmudict # $ pip install nltk# $ python -c "import nltk; nltk.download('cmudict')"def spubeak(word, pronunciations=cmudict.dict()): istitle = word.istitle() # remember, to preserve titlecase w = word.lower() #note: ignore Unipre case-folding for syllables in pronunciations.get(w, []): parts = [] for syl in syllables: if syl[:1] == syl[1:2]: syl = syl[1:] # remove duplicate isvowel = syl[-1].isdigit() # pronounce the word parts.append('ub'+syl[:-1] if isvowel else syl) result = ''.join(map(str.lower, parts)) return result.title() if istitle else result return word # word not found in the dictionary例:
#!/usr/bin/env python# -*- coding: utf-8 -*-import resent = "Hi, how are you?"subent = " ".join(["".join(map(spubeak, re.split("(W+)", nonblank))) for nonblank in sent.split()])print('"{}" → "{}"'.format(sent, subent))输出量
“你好你好吗?” →“ Hubay,hubo ubar yubuw?”
注意:它与第一个示例不同:每个单词都用其音节替换。



