聚会有点晚了,但我正在做一个项目,以找到许多押韵线进行处理。我从这个问题线程开始,并被kender 接受的答案引发。很高兴知道,在识别成千上万的韵律时,您可以利用字典查找来大大提高速度。
这也针对 python 3.x 进行了更新。
将 CMU 发音字典存储为 json 文件,其中包含一个 init 函数和一个将条目从元组转换为字典的函数。
# global
json_entries = None
def tup2dict(tup, di):
for a, b in tup:
di.setdefault(a, []).append(b)
return di
def init_cmu(args):
import nltk
nltk.download('cmudict')
nltk.corpus.cmudict.ensure_loaded()
cmu_entries = nltk.corpus.cmudict.entries()
cmu_dict = dict()
tup2dict(cmu_entries, cmu_dict)
with open('./maps/cmu.json', 'w') as convert_file:
convert_file.write(json.dumps(cmu_dict))
如果您在脚本中使用了需要确定韵律的函数,则可以在其顶部调用此函数以确保您可以访问字典。
def require_rhyme_dict():
global json_entries
if json_entries:
return
try:
jsonf = open('./maps/cmu.json', 'r')
except:
pass
else:
# Global
json_entries = dict(json.load(jsonf))
jsonf.close()
print('json_entries loaded.')
最后,这是kender 的押韵功能的修改版本,它使用字典和不同的子词检查方法(我遇到了一些极端情况,押韵不是“跛脚”,但单词是'不允许根据词首索引和长度押韵。具体例子记不清了,很少见)。
当连续调用数千次时,下面的函数调用比一旦找到一个单词就遍历所有nltk cmu条目以查找发音音节列表要快得多。与以前一样,级别是指单词之间的多少发音音节,匹配在末尾找到的那些,应该匹配以构成押韵。在本例中,如果有多个发音,也会检查每个单词的发音。
def isContainSameWord(word1, word2):
if word1 in word2 or word2 in word1:
return True
else:
return False
def isRhyme(word1, word2, level):
require_rhyme_dict()
global json_entries
if isContainSameWord(word1, word2):
return False
word1_syllable_arrs = json_entries.get(word1)
word2_syllables_arrs = json_entries.get(word2)
if not word1_syllable_arrs or not word2_syllables_arrs:
return False
for a in word1_syllable_arrs:
for b in word2_syllables_arrs:
if a[-level:] == b[-level:]:
return True
return False