python实现成语接龙 | Hlwdy's blog
python实现成语接龙
发表于 2020-04-08 共 621 字
分类于 python

python实现成语接龙

成语接龙是中华民族传统的文字游戏。它不仅有着悠久的历史和广泛的社会基础,同时还是体现我国文字、文化、文明的一个缩影,是老少皆宜的民间文化娱乐活动。 成语接龙规则多样,大家一般熟知的是采用成语字头与字尾相连不断延伸的方法进行接龙;因为成语接龙是作为一种广泛开展的群众性竞争游戏出现的,所以它应该有一个权威、严密的规范方法,以体现游戏的公平、公正。使佼佼者脱颖而出。

那么在python里面如何实现自动成语接龙呢?

涉及到成语储备,我们当然就要准备一个词库,(这里准备了一个data.txt,文章末尾会提供下载)

而成语接龙一般有两种:

于是我们这里实现两种模式,(0为首字,1为首字拼音)

使用pinyin库进行获取拼音并进行匹配,完整代码如下:

import pinyin,random

data = []
def get_pinyin(word):
    pinyins = []
    for i in word:
        pinyins.append(pinyin.get(i, format='strip', delimiter=" "))
    return pinyins

def get_all_starts_with(letter):
    result = []
    target_pinyin = get_pinyin(letter)
    target_pinyin_first = target_pinyin[-1]
    for i in data:
        data_word = i[0]
        data_pinyin = i[1]
        data_meaning = i[2]
        data_pinyin_first = data_pinyin[0]
        if data_pinyin_first == target_pinyin_first:
            result.append([data_word, data_meaning])
    return result

def get_all_starts_with_zi(letter):
    result = []
    target_first = letter[-1:]
    for i in data:
        data_word = i[0]
        data_meaning = i[2]
        data_first = data_word[0]
        if data_first == target_first:
            result.append([data_word, data_meaning])
    return result

def get_random_result(data):
    return random.choice(data)

def format_data(data):
    return "[%s] : [%s]" % (data[0], data[1])

def init():
    with open("data.txt", "rb") as f:
        counter = 0
        for line in f:
            content = line.decode("UTF-8").split("\t")
            word = content[0]
            pinyin = content[1].split("'")
            meaning = content[2].replace("\n", "")
            data.append([word, pinyin, meaning])
            counter += 1

init()
mode=int(input('mode: '))
while(True):
    word = input('input: ')
    if(mode==0):
        all_data_matched = get_all_starts_with(word)
    else:
        all_data_matched = get_all_starts_with_zi(word)
    result_data = format_data(get_random_result(all_data_matched))
    print(result_data)

很容易看出来,这里就是从本地读取data.txt,存入数组,每次匹配时随机抽取一个匹配结果并输出

思路很简单,就是首尾相匹配

最后献上成语词库(包括成语,拼音及解释,数据均来自互联网,词库并非本人所制作)

链接: https://share.weiyun.com/5aYhDK1 (密码:FdDp)

筛选文章
类别选择 (分类/标签)
全屏 关闭