示例: Speak -> Spubeak, 更多信息请点击此处
请不要直接给我解决方案,而是指出正确的方向或告诉我可以使用哪个Python库?我考虑使用正则表达式,因为我需要找到元音字母,但我应该使用哪个方法在元音字母前插入'ub'呢?
示例: Speak -> Spubeak, 更多信息请点击此处
请不要直接给我解决方案,而是指出正确的方向或告诉我可以使用哪个Python库?我考虑使用正则表达式,因为我需要找到元音字母,但我应该使用哪个方法在元音字母前插入'ub'呢?
它比简单的正则表达式(例如)更加复杂。
"Hi, how are you?" → "Hubi, hubow ubare yubou?"
简单的正则表达式无法捕捉到are
中的e
是不发音的。
您需要使用提供发音字典的库,例如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?"
注意:这与第一个示例不同:每个单词都被其音节替换。
re.sub
。>>> import re
>>> re.sub(r'(e)', r'ub\1', 'speak')
'spubeak'
正则表达式确实是最佳选择。如果您不确定如何继续,请查看捕获组的工作原理以及如何在替换中使用它们。
ub
的形式来实现,从而使正则表达式部分变得不必要。更糟糕的是,在这种情况下,原始问题仍然存在。 - Platinum Azure