Home ยป Using a Pronouncing library in Python

Using a Pronouncing library in Python

Pronouncing is a simple interface for the CMU Pronouncing Dictionary.

The Carnegie Mellon University Pronouncing Dictionary is an open-source machine-readable pronunciation dictionary for North American English that contains over 134,000 words and their pronunciations.

Installation

Install with pip like so:

pip install pronouncing

Examples

Rhyming words example

Here we see a basic example which will do the following

  • We have imported the pronouncing module as pronounce in the program to use this module’s rhymes() function.
  • After that, we use the rhymes() function and used the ‘bright’ word in it so that all rhyming words related to the ‘bright’ word will be returned.
  • We store the result of this in the rhymeResults variable so that we can use this variable to print the result.
  • Then we print the rhymeResults variable to print out the rhyming words related to ‘bright’ in the output.
# Importing the pronouncing module  
import pronouncing as pronounce

# Using rhymes() for finding rhyming words  
rhymeResults = pronounce.rhymes("bright")

# Printing result in the output  
print("The rhyming words of the word bright are: ")  
print(rhymeResults)  

This returned the following, I have truncated the list

>>> %Run pronouncingword.py
The rhyming words of the word bright are: 
['alight', 'allright', 'alright', 'beit', 'benight', 'bight', 'zeit']

Counting syllables

You can get the number of syllables in a word, first get one of its pronunciations with pronouncing.phones_for_word() and pass the resulting string of phones to the pronouncing.syllable_count() function.

import pronouncing
text = "this is the sample text to check"
phones = [pronouncing.phones_for_word(p)[0] for p in text.split()]
print (sum([pronouncing.syllable_count(p) for p in phones]))

This returned 8.

Randomly replacing words

One neat thing you can do is to replace the words in your string with others, if other words are found for that word.

Lets see an example

import pronouncing
import random

text = 'this is the sample text to replace certain words in'
out = list()

for word in text.split():
    rhymes = pronouncing.rhymes(word)
    if len(rhymes) > 0:
        out.append(random.choice(rhymes))
    else:
        out.append(word)

print (' '.join(out))

I saw the following returned

>>> %Run pronouncingreplace.py
abyss wiz the trample sexed bleu place uncertain herds in

Links

code on github

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More