成语接龙改版

1、概述

上一版的成语接龙中,对汉字进行了严格匹配,我们会发现,在这种情况下,成语接龙的长度很短。如下图所示:

原因是什么呢,因为我们一般在玩成语接龙游戏时遵循的原则是可以音同字不同。给予这种需求,我们对之前的代码进行一次改版

2、代码实现

这里我们使用了xpinyin库,这个库的主要功能是将汉字转为拼音,这里也可以看到python作为一种胶水语言方便易用的特性。请参考如下代码。

import random
max_count = 50
selected_words = []
start_word = '一'
start_pinyin = p.get_pinyin(start_word)
for i in range(50):
    start_data = [w[1] for w in data if w[0]==start_pinyin and w[1] not in selected_words]
    if len(start_data)==0:
        break
    current_word=start_data[random.randint(0,len(start_data)-1)]
    print(current_word)
    selected_words.append(current_word)
    start_pinyin = p.get_pinyin(current_word[-1])

输出效果如下图所示:

猜你喜欢

转载自blog.csdn.net/amao1998/article/details/83213803