Python:如何将字符串 'ub' 添加到字符串中每个发音的元音前?

标签 python regex string nlp

示例:说话 -> Spubeak,more info here

不要给我一个解决方案,而是给我指出正确的方向或告诉我可以使用哪个 python 库?我正在考虑正则表达式,因为我必须找到一个元音字母,但是我可以使用哪种方法在元音字母前插入“ub”?

最佳答案

它比一个简单的正则表达式更复杂 e.g.,

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

简单的正则表达式不会捕捉到 eare 中不发音。

你需要一个提供发音词典的库,比如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/

相关文章:

python - 阻止机器人抓取我的 Google App Engine 网站

regex - grep 有效域正则表达式

java - 修剪月份正则表达式的名称

Javascript/jQuery 使用正则表达式搜索 "minute:second"时间

python - 如何在Python中的第二个字符匹配上分割字符串?

c 读取字符串导致崩溃

python - SK学习: TypeError: __init__() got an unexpected keyword argument n_splits

python - 为什么我没有从列表理解检查真值中获得索引返回?

python - wx.TextCtrl .write/.WriteText/.AppendText 之间的区别

c - 将输入文本中的十六进制值保存到字符串 var,反之亦然 ANSI C