示例:说话 -> Spubeak,more info here
不要给我一个解决方案,而是给我指出正确的方向或告诉我可以使用哪个 python 库?我正在考虑正则表达式,因为我必须找到一个元音字母,但是我可以使用哪种方法在元音字母前插入“ub”?
最佳答案
它比一个简单的正则表达式更复杂 e.g.,
"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 Unicode 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 re
sent = "Hi, how are you?"
subent = " ".join(["".join(map(spubeak, re.split("(\W+)", nonblank)))
for nonblank in sent.split()])
print('"{}" → "{}"'.format(sent, subent))
输出
"Hi, how are you?" → "Hubay, hubaw ubar yubuw?"
注意:它与第一个示例不同:每个单词都用其音节替换。
关于Python:如何将字符串 'ub' 添加到字符串中每个发音的元音前?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9505714/