#python# 成语接龙(二)


寻找可以“一招制敌”的成语。

接上一篇:#python# 成语接龙(一)

# encoding=utf8

import matplotlib.pyplot as plt

def get_idioms(file):
    """
    获取所有成语
    返回值:[ ['正襟危坐', 'zheng.jin.wei.zuo'], ['正人君子', 'zheng.ren.jun.zi'], ... ]
    """
    idioms = []    
    with open(file, "r") as f:
        idioms = [x.strip('\n').split(' ') for x in f.readlines()]
    return idioms
    
def get_start_pinyin_set(idioms):
    """
    获取成语的第一个字的拼音集合
    """
    start_pinyin_set = {}    
    for idiom in idioms:
        [hz, py] = idiom
        start = py.split('.')[0]  # 成语第一个字拼音
        if start not in start_pinyin_set:
            start_pinyin_set[start] = [(hz, py)]        
        else:
            start_pinyin_set[start].append((hz, py))    
    return start_pinyin_set
    
def check_idiom_dead(idioms, start_pinyin_set):
    """
    找出无法被接龙的成语
    """
    idiom_dead = {}    
    for idiom in idioms:
        [hz, py] = idiom
        last = py.split('.')[-1]  # 成语最后一个字拼音
        if last not in start_pinyin_set:            
            if last not in idiom_dead:
                idiom_dead[last] = [(hz, py)]            
            else:
                idiom_dead[last].append([(hz, py)])    
    return idiom_dead
    
def idiom_dead_stat(idiom_dead):
    """
    统计无法被接龙成语的最后一个字的拼音
    """
    data = sorted([(len(idiom_dead[py]), py)                   
                    for py in idiom_dead], reverse=True)
    y = [d[0] for d in data]
    y_py = [d[1] for d in data]
    x = range(0, len(y))

    plt.figure(figsize=(10, 6))
    plt.bar(x, y, color='g')
    plt.xticks(x, y_py)
    plt.title('idiom dead', y=0.9)
    plt.show()    
    pass

if __name__ == "__main__":
    idioms = get_idioms(u"成语大全.txt")
    start_pinyin_set = get_start_pinyin_set(idioms)
    idiom_dead = check_idiom_dead(idioms, start_pinyin_set)
    idiom_dead_stat(idiom_dead)    
    pass

统计结果:

(↓ - 有些内容只在小龙家发,可关注同名“趣Python”号,谢谢 - ↓) 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值