前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >#python# 成语接龙(二)

#python# 成语接龙(二)

作者头像
滚神大人
发布2019-09-10 19:48:28
6830
发布2019-09-10 19:48:28
举报
文章被收录于专栏:趣Python趣Python

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

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

代码语言:javascript
复制
# 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

统计结果:

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-12-25,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 趣Python 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档