python-2.7 - 从 Python NLTK 或其他模块中的任何单词中获取音素?

标签 python-2.7 nltk

Python NLTK 有 cmudict 可以吐出已识别单词的音素。例如 'see' -> [u'S', u'IY1'],但对于无法识别的单词,它会给出错误。例如“seasee”-> 错误。

import nltk

arpabet = nltk.corpus.cmudict.dict()

for word in ('s', 'see', 'sea', 'compute', 'comput', 'seesea'):
    try:
        print arpabet[word][0]
    except Exception as e:
        print e

#Output
[u'EH1', u'S']
[u'S', u'IY1']
[u'S', u'IY1']
[u'K', u'AH0', u'M', u'P', u'Y', u'UW1', u'T']
'comput'
'seesea'

是否有任何模块没有该限制但能够找到/猜测任何真实或虚构单词的音素?

如果没有,有什么办法可以编程吗?我正在考虑做循环来测试单词的增加部分。例如,在“seasee”中,第一个循环采用“s”,下一个循环采用“se”,第三个采用“sea”……等等并运行 cmudict。虽然问题是我不知道如何表示它是要考虑的正确音素。例如,“seasee”中的“s”和“sea”都会输出一些有效的音素。

工作进度:
import nltk

arpabet = nltk.corpus.cmudict.dict()

for word in ('s', 'see', 'sea', 'compute', 'comput', 'seesea', 'darfasasawwa'):
    try:
        phone = arpabet[word][0]
    except:
        try:
            counter = 0
            for i in word:
                substring = word[0:1+counter]
                counter += 1
                try:
                    print substring, arpabet[substring][0]
                except Exception as e:
                    print e
        except Exception as e:
            print e

#Output
c [u'S', u'IY1']
co [u'K', u'OW1']
com [u'K', u'AA1', u'M']
comp [u'K', u'AA1', u'M', u'P']
compu [u'K', u'AA1', u'M', u'P', u'Y', u'UW0']
comput 'comput'
s [u'EH1', u'S']
se [u'S', u'AW2', u'TH', u'IY1', u'S', u'T']
see [u'S', u'IY1']
sees [u'S', u'IY1', u'Z']
seese [u'S', u'IY1', u'Z']
seesea 'seesea'
d [u'D', u'IY1']
da [u'D', u'AA1']
dar [u'D', u'AA1', u'R']
darf 'darf'
darfa 'darfa'
darfas 'darfas'
darfasa 'darfasa'
darfasas 'darfasas'
darfasasa 'darfasasa'
darfasasaw 'darfasasaw'
darfasasaww 'darfasasaww'
darfasasawwa 'darfasasawwa'

最佳答案

我遇到了同样的问题,我通过递归划分未知数解决了它(见 wordbreak )

import nltk
from functools import lru_cache
from itertools import product as iterprod

try:
    arpabet = nltk.corpus.cmudict.dict()
except LookupError:
    nltk.download('cmudict')
    arpabet = nltk.corpus.cmudict.dict()

@lru_cache()
def wordbreak(s):
    s = s.lower()
    if s in arpabet:
        return arpabet[s]
    middle = len(s)/2
    partition = sorted(list(range(len(s))), key=lambda x: (x-middle)**2-x)
    for i in partition:
        pre, suf = (s[:i], s[i:])
        if pre in arpabet and wordbreak(suf) is not None:
            return [x+y for x,y in iterprod(arpabet[pre], wordbreak(suf))]
    return None

关于python-2.7 - 从 Python NLTK 或其他模块中的任何单词中获取音素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33666557/

相关文章:

python - 如何使用python给文本添加标点符号?

Python - 分组顺序数组成员

python - NLTK 是否实现了 TF-IDF?

python-2.7 - 奇怪的迭代结果 "error is nan"和使用 t-SNE 的 RuntimeWarning

python - 使用 BeautifulSoup 提取 <script> 的内容

python - 当外部函数 stdout 发生时将其重定向到日志文件

python - 我可以创建一个可以解包的类吗?

python - 如何在 python 中打印毕达哥拉斯金字塔?

sql - 在 NLTK 中将英语转换为 SQL

python - 如何分批训练 NLTK PunktSentenceTokenizer?