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])
輸出效果如下圖所示: