擅长:python、mysql、java
<p><a href="http://kashthealien.wordpress.com/2013/06/15/213/" rel="nofollow noreferrer">Here</a>我找到了一种使用NLTK查找给定单词押韵的方法:</p>
<pre><code>def rhyme(inp, level):
entries = nltk.corpus.cmudict.entries()
syllables = [(word, syl) for word, syl in entries if word == inp]
rhymes = []
for (word, syllable) in syllables:
rhymes += [word for word, pron in entries if pron[-level:] == syllable[-level:]]
return set(rhymes)
</code></pre>
<p>其中<code>inp</code>是一个单词,<code>level</code>意味着押韵应该有多好。</p>
<p>因此,您可以使用此函数来检查两个单词是否押韵,您可以只检查其中一个单词是否在另一个单词的允许押韵集中:</p>
<pre><code>def doTheyRhyme(word1, word2):
# first, we don't want to report 'glue' and 'unglue' as rhyming words
# those kind of rhymes are LAME
if word1.find(word2) == len(word1) - len(word2):
return False
if word2.find(word1) == len(word2) - len(word1):
return False
return word1 in rhyme(word2, 1)
</code></pre>