Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

regex - Python: How to prepend the string 'ub' to every pronounced vowel in a string?

Example: Speak -> Spubeak, more info here

Don't give me a solution, but point me in the right direction or tell which which python library I could use? I am thinking of regex since I have to find a vowel, but then which method could I use to insert 'ub' in front of a vowel?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is more complex then just a simple regex e.g.,

"Hi, how are you?" → "Hubi, hubow ubare yubou?"

Simple regex won't catch that e is not pronounced in are.

You need a library that provides a pronunciation dictionary such as 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

Example:

#!/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))

Output

"Hi, how are you?" → "Hubay, hubaw ubar yubuw?"

Note: It is different from the first example: each word is replaced with its syllables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...