基于Python经典版成语接龙逻辑实现

  今天,想检验一下前期Python学习成功,加上好友提起斗一波成语接龙,为完全碾压,轻松取胜,便顺手写一个适合日常群聊PK的成语接龙小程序。具体实现流程如下:

  成语俗语词库下载

  前往搜狗输入法官网,找到词库页面,搜索成语,定位进入 成语俗语 页面, 下载 官方词库 -- 成语俗语【官方推荐】.scel

  搜狗成语俗语词库转txt备用

  github上有现成的scel转txt的代码,此处个人调试为适用python3.6的版本

import struct
import os# 搜狗的scel词库就是保存的文本的unicode编码,每两个字节一个字符(中文汉字或者英文字母)
# 找出其每部分的偏移位置即可
# 主要两部分
# 1.全局拼音表,貌似是所有的拼音组合,字典序
#       格式为(index,len,pinyin)的列表
#       index: 两个字节的整数 代表这个拼音的索引
#       len: 两个字节的整数 拼音的字节长度
#       pinyin: 当前的拼音,每个字符两个字节,总长len
#
# 2.汉语词组表
#       格式为(same,py_table_len,py_table,{word_len,word,ext_len,ext})的一个列表
#       same: 两个字节 整数 同音词数量
#       py_table_len:  两个字节 整数
#       py_table: 整数列表,每个整数两个字节,每个整数代表一个拼音的索引
#
#       word_len:两个字节 整数 代表中文词组字节数长度
#       word: 中文词组,每个中文汉字两个字节,总长度word_len
#       ext_len: 两个字节 整数 代表扩展信息的长度,好像都是10
#       ext: 扩展信息 前两个字节是一个整数(不知道是不是词频) 后八个字节全是0
#
#      {word_len,word,ext_len,ext} 一共重复same次 同音词 相同拼音表# 拼音表偏移,
startPy = 0x1540;# 汉语词组表偏移
startChinese = 0x2628;# 全局拼音表
GPy_Table = {}# 解析结果
# 元组(词频,拼音,中文词组)的列表
GTable = []# 原始字节码转为字符串
def byte2str(data):pos = 0str = ''while pos < len(data):c = chr(struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0])if c != chr(0):str += cpos += 2return str# 获取拼音表
def getPyTable(data):data = data[4:]pos = 0while pos < len(data):index = struct.unpack('H', bytes([data[pos],data[pos + 1]]))[0]pos += 2lenPy = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]pos += 2py = byte2str(data[pos:pos + lenPy])GPy_Table[index] = pypos += lenPy# 获取一个词组的拼音
def getWordPy(data):pos = 0ret = ''while pos < len(data):index = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]ret += GPy_Table[index]pos += 2return ret# 读取中文表
def getChinese(data):pos = 0while pos < len(data):# 同音词数量same = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]# 拼音索引表长度pos += 2py_table_len = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]# 拼音索引表pos += 2py = getWordPy(data[pos: pos + py_table_len])# 中文词组pos += py_table_lenfor i in range(same):# 中文词组长度c_len = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]# 中文词组pos += 2word = byte2str(data[pos: pos + c_len])# 扩展数据长度pos += c_lenext_len = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]# 词频pos += 2count = struct.unpack('H', bytes([data[pos], data[pos + 1]]))[0]# 保存GTable.append((count, py, word))# 到下个词的偏移位置pos += ext_lendef scel2txt(file_name):print('-' * 60)with open(file_name, 'rb') as f:data = f.read()print("词库名:", byte2str(data[0x130:0x338])) # .encode('GB18030')print("词库类型:", byte2str(data[0x338:0x540]))print("描述信息:", byte2str(data[0x540:0xd40]))print("词库示例:", byte2str(data[0xd40:startPy]))getPyTable(data[startPy:startChinese])getChinese(data[startChinese:])if __name__ == '__main__':# scel所在文件夹路径in_path = "E:\python_workspace"# 输出词典所在文件夹路径out_path = "coal_dict.txt"fin = [fname for fname in os.listdir(in_path) if fname[-5:] == ".scel"]for f in fin:f = os.path.join(in_path, f)scel2txt(f)# 保存结果with open(out_path, 'w', encoding='utf8') as f:f.writelines([word+'\n' for count, py, word in GTable])

  业务逻辑实现

from IPython.core.interactiveshell import InteractiveShellInteractiveShell.ast_node_interactivity = "all"from pypinyin import pinyin, lazy_pinyin, Styleidiom_dic = {}
idiom_list = []
idiom_char_dic = {}with open('E:\python_workspace\coal_dict.txt', 'r', encoding='utf8') as r:for line in r:line = line.strip()if None == line or line == '':continueidiom_list.append(line)key = lazy_pinyin(line)[0]value = ''if key in idiom_dic.keys():value = idiom_dic[key] + ',' + lineelse:value = lineidiom_dic[key] = value# 汉字接龙key_char = line[0]value_char = ''if key_char in idiom_char_dic.keys():value_char = idiom_char_dic[key_char] + ',' + lineelse:value_char = lineidiom_char_dic[key_char] = value_char# 汉字接龙,polyphone -- 是否匹配读音
def idiom_next_char(idiom, polyphone=False):if idiom not in idiom_list:res = idiom + ' is not one idiom'else:last = idiom[len(idiom) - 1]if polyphone:passif last not in idiom_char_dic:res = 'library without the supply idioms'else:aa = idiom_char_dic[last]last = lazy_pinyin(idiom)[len(idiom) - 1]bb = idiom_dic[last]aa_list = aa.split(',')bb_list = bb.split(',')cd_list = set(aa_list).intersection(set(bb_list))  # 求并集res = ','.join(cd_list)else:if last not in idiom_char_dic:res = 'library without the supply idioms'else:res = idiom_char_dic[last]return res# 拼音接龙
def idiom_next(idiom):if idiom not in idiom_list:res = idiom + ' is not one idiom'else:last = lazy_pinyin(idiom)[len(idiom) - 1]if last not in idiom_dic:res = 'library without the supply idioms'else:res = idiom_dic[last]return res# print(idiom_next('怒发冲冠'))# 汉字定长接龙
def idiom_multi_char_length(idiom, length=10, polyphone=False):index = 0res_list = [idiom]while index < length:res = idiom_next_char(idiom, polyphone)if 'idiom' in res:breakelse:res_next = res.split(',')idiom = res_next[0]res_list.append(idiom)index = index + 1return res_list# 拼音定长接龙
def idiom_multi_length(idiom, length=10):index = 0res_list = [idiom]while index < length:res = idiom_next(idiom)if 'idiom' in res:breakelse:res_next = res.split(',')idiom = res_next[0]res_list.append(idiom)index = index + 1return res_listdef check_none_follow_list():none_follow = []for idiom in idiom_list:res = idiom_next(idiom)if 'idiom' in res:none_follow.append(idiom)return none_follow# none_supply = check_none_follow_list()
# print(none_supply)

  简单调试

  pycharm 2018.2版本依赖,支持 运行调试功能,即即直接加载 .py 代码到内存,可以直接调用声明的函数和变量,打开方式:Run/Debug Configurations -- Configuration -- Execution -- Run with Python console。

  这样调试尤其便利:

  1、成语接龙(读音匹配)

idiom_multi_length('刻舟求剑')
Out[6]:
['刻舟求剑','兼爱无私','死败涂地','低昂不就','灸艾分痛','同胞共气','期月有成','撑岸就船','传杯换盏','粘皮带骨','告朔饩羊']

  2、成语接龙(汉字匹配)

idiom_multi_char_length('刻舟求剑')
Out[5]:
['刻舟求剑','剑拔弩张','张本继末','末大必折','折本买卖','卖卜测字','字挟风霜','霜刀小径','径情而行','行行出状元','元恶大憝']

  3、成语接龙(汉字、读音匹配)

idiom_multi_char_length('刻舟求剑',polyphone=True)
Out[7]:
['刻舟求剑','剑拔弩张','张冠李戴','戴凭夺席','席丰履厚','厚貌深情','情恕理遣','遣将调兵','兵来将挡水来土掩','掩耳不闻','闻弦歌而知雅意']

转载于:https://www.cnblogs.com/nyatom/p/10913307.html

基于Python经典版成语接龙逻辑实现相关推荐

  1. python的成语接龙程序代码_基于Python经典版成语接龙逻辑实现

    import structimport os # 搜狗的scel词库就是保存的文本的unicode编码,每两个字节一个字符(中文汉字或者英文字母) # 找出其每部分的偏移位置即可 # 主要两部分 #1 ...

  2. python成语接龙代码_基于Python经典版成语接龙逻辑实现

    import structimport os # 搜狗的scel词库就是保存的文本的unicode编码,每两个字节一个字符(中文汉字或者英文字母) # 找出其每部分的偏移位置即可 # 主要两部分 #1 ...

  3. 学富五车的你,敢迎战Python开发的成语接龙游戏吗?

    成语接龙 今天难得下班早,不用做公司的末班车,和同事乘公交回家.中途上来几个学生,相互在玩着成语接龙游戏.说是成语,但词汇却真是不堪入耳. 6月高考的前一天,我发布的一篇文章,决战高考,帮你秒变成语之 ...

  4. 学富五车的你,敢来迎战Python开发的成语接龙游戏吗?

    点击上方"Python爬虫与数据挖掘",进行关注 回复"书籍"即可获赠Python从入门到进阶共10本电子书 今 日 鸡 汤 真者,精诚之至也,不精不诚,不能动 ...

  5. 敢来迎战Python开发的成语接龙游戏吗?

    游戏演示 说了这么多,让我们来先睹为快,让我来挑战一局接龙比赛吧: <游戏展示> 既然是游戏,就得来个排名才有意思啊! 之前测试了几轮数据,这次我们使用一个Neo的新用户来进行游戏,随便接 ...

  6. python 实现的 成语接龙

    点这里安装 => 成语接龙 JioNLP 安装 Installation python>=3.6 $ git clone https://github.com/dongrixinyu/Ji ...

  7. 还在怕成语接龙你玩不过别人嘛!今天教大家用Python做一个成语接龙的小游戏!!!

    相关文件 关注小编,私信小编领取源码哟!!当然别忘了一键三连哟!! 开发工具 Python版本:3.6.4 相关模块: pyqt5模块: 以及一些python自带的模块. 环境搭建 安装Python并 ...

  8. python中成语接龙游戏_Python实现成语接龙

    这是一篇用Python实现成语接龙小游戏的具体开发教程.Python实现这个功能非常容易,以下分为两个版本,一个是简易版,能够实现基本的功能.还有一个是拓展版,是在简易版上进行拓展,功能更为复杂且完善 ...

  9. 成语接龙python

    用python编写一个成语接龙: # 读取 成语大全.txt f = open("成语大全.txt", "r",encoding="ANSI" ...

最新文章

  1. 火山引擎向企业客户开放上万款抖音同款特效
  2. java变量设置_配置环境变量
  3. 清空SQL Server数据库日志的SQL语句
  4. 区块链新经济蓝图及导读pdf_区块链加快产业数字化转型,区块链新零售模式为企业发展加码提速...
  5. 网络营销推广软件教你学会单页面SEO优化技巧,轻松赢流量!
  6. .NET C/S(WinForm)开发技巧点滴(转)
  7. p中div -- a中a
  8. Codeforces Round #737 (Div. 2)
  9. PHP ajax跨域问题最佳解决方案
  10. WindowsXP下搭建GIT服务器
  11. 如何将txt中的数据整理到Matlab中画图
  12. Java正则表达式之Matcher类的find和matches方法的区别
  13. 关于MacOS升级10.13系统eclipse菜单灰色无法使用解决方案
  14. 从国产手机自强复盘小米十年
  15. 冷水机组选型公式与运行参数
  16. 宏碁公司再次遭遇入侵,160GB敏感数据泄露
  17. android高德轨迹纠偏,轨迹纠偏-服务-教程-地图 JS API | 高德地图API
  18. DES加密算法的C++实现
  19. 经典书摘:基于信用本质,区块链应用的9大场景
  20. C#按行读取、写入txt文件

热门文章

  1. bat文件调用CMD命令快速显示ip
  2. 关于音乐制作的一些网站
  3. Kubernetes学习
  4. 激光雷达和相机的联合标定
  5. 【阿朱标红】O2O五年三次创业的九大经验(天天用车CEO翟光龙)
  6. 如何将弹幕嵌入视频中,合成一个文件
  7. 四年上册级计算机教学计划,2021年四年级信息技术教学计划集锦5篇
  8. linux wol 戴尔工作站,linux 通过wol远程开机【转】
  9. 网盘直链下载 windows 和 mac 都能使用 (油猴+FMD+直链脚本)
  10. 用了基木鱼还用网站服务器吗,基木鱼操作手册:营销通相关问题