当前位置:   article > 正文

用 Python 自制成语接龙小游戏!

python成语接龙

作者:小小明

来源:杰哥的IT之旅

在 https://github.com/pwxcoo/chinese-xinhua 项目中可以下载到中华成语的语料库,该项目收录包括 14032 条歇后语,16142 个汉字,264434 个词语,31648 个成语。

结构如下:

  1. chinese-xinhua/
  2. |
  3. +- data/ <-- 数据文件夹
  4. |  |
  5. |  +- idiom.json <-- 成语
  6. |  |
  7. |  +- word.json <-- 汉字
  8. |  |
  9. |  +- xiehouyu.json <-- 歇后语
  10. |  |
  11. |  +- ci.json <-- 词语

可以直接从网络读取该github的json文件:

  1. import pandas as pd
  2. chengyu = pd.read_json(
  3.     "https://github.com/pwxcoo/chinese-xinhua/blob/master/data/idiom.json?raw=true")

不过有可能网络不佳导致读取失败,下载好之后读取本地文件更佳:

  1. import pandas as pd
  2. import numpy as np
  3. chengyu = pd.read_json("idiom.json")
  4. chengyu.head(2)

该库有很多列,word列是我们需要的成语,pinyin列已经帮我们转换出了对应的拼音。下面我们整理出我们需要的数据:

  1. t = chengyu.pinyin.str.split()
  2. chengyu["shoupin"] = t.str[0]
  3. chengyu["weipin"] = t.str[-1]
  4. chengyu = chengyu.set_index("word")[["shoupin""weipin"]]
  5. chengyu

测试获取任意一个成语的接龙结果集:

  1. word = "阿党比周"
  2. words = chengyu.index[chengyu.shoupin == chengyu.loc[word, "weipin"]]
  3. words
  4. Index(['舟车劳顿''舟水之喻''舟中敌国''诌上抑下''侜张为幻''周而不比''周而复始''周公吐哺''周规折矩',
  5.        '周急继乏''周郎顾曲''周情孔思''周穷恤匮''周游列国''诪张变眩''诪张为幻''粥少僧多''粥粥无能'],
  6.       dtype='object', name='word')

然后随机任取一个:

  1. np.random.choice(words)
  2. '诪张为幻'

测试没有问题,我们可以写一个批量接龙程序:

  1. word = input("请输入一个成语:")
  2. flag = True
  3. if word not in chengyu.index:
  4.     print("你输入的不是一个成语,程序结束!")
  5.     flag = False
  6. while flag:
  7.     n = input("接龙的次数(1-100次的整数,输入任意字母表示结束程序)")
  8.     if not n.isdigit():
  9.         print("程序结束")
  10.         break
  11.     n = int(n)
  12.     if not (0 < n <= 100):
  13.         print("非法数字,程序结束")
  14.         break
  15.     for _ in range(n):
  16.         words = chengyu.index[chengyu.shoupin == chengyu.loc[word, "weipin"]]
  17.         if words.shape[0] == 0:
  18.             print("没有找到可以接龙的成语,程序结束")
  19.             flag = False
  20.             break
  21.         word = np.random.choice(words)
  22.         print(word)

  1. 请输入一个成语:周郎顾曲
  2. 接下来程序自动接龙的次数(1-100次的整数,其他情况表示结束)10
  3. 曲尽奇妙
  4. 妙趣横生
  5. 声应气求
  6. 求人不如求己
  7. 掎挈伺诈
  8. 诈痴不颠
  9. 颠乾倒坤
  10. 昆山之玉
  11. 玉叶金枝
  12. 织当访婢
  13. 接下来程序自动接龙的次数(1-100次的整数,其他情况表示结束)no
  14. 结束

完整代码

  1. import pandas as pd
  2. import numpy as np
  3. chengyu = pd.read_json("idiom.json")
  4. t = chengyu.pinyin.str.split()
  5. chengyu["shoupin"] = t.str[0]
  6. chengyu["weipin"] = t.str[-1]
  7. chengyu = chengyu.set_index("word")[["shoupin""weipin"]]
  8. word = input("请输入一个成语:")
  9. flag = True
  10. if word not in chengyu.index:
  11.     print("你输入的不是一个成语,程序结束!")
  12.     flag = False
  13. while flag:
  14.     n = input("接龙的次数(1-100次的整数,输入任意字母表示结束程序)")
  15.     if not n.isdigit():
  16.         print("程序结束")
  17.         break
  18.     n = int(n)
  19.     if not (0 < n <= 100):
  20.         print("非法数字,程序结束")
  21.         break
  22.     for _ in range(n):
  23.         words = chengyu.index[chengyu.shoupin == chengyu.loc[word, "weipin"]]
  24.         if words.shape[0] == 0:
  25.             print("没有找到可以接龙的成语,程序结束")
  26.             flag = False
  27.             break
  28.         word = np.random.choice(words)
  29.         print(word)

我们还可以写一个与机器对战的成语接龙小游戏:

  1. import pandas as pd
  2. import numpy as np
  3. chengyu = pd.read_json("idiom.json")
  4. t = chengyu.pinyin.str.split()
  5. chengyu["shoupin"] = t.str[0]
  6. chengyu["weipin"] = t.str[-1]
  7. chengyu = chengyu.set_index("word")[["shoupin""weipin"]]
  8. is_head = input("是否先手(输入N表示后手,其他表示先手)")
  9. if is_head == "N":
  10.     word2 = np.random.choice(chengyu.index)
  11.     print(word2)
  12.     weipin = chengyu.loc[word2, "weipin"]
  13. else:
  14.     weipin = ''
  15. while True:
  16.     word = input("请输入一个成语(认输或离开请按Q):")
  17.     if word == "Q":
  18.         print("你离开了游戏,再见!!!")
  19.         break
  20.     if word not in chengyu.index:
  21.         print("你输入的不是一个成语,请重新输入!")
  22.         continue
  23.     if weipin and chengyu.loc[word, 'shoupin'] != weipin:
  24.         print("你输入的成语并不能与机器人出的成语接上来,你输了,游戏结束!!!")
  25.         break
  26.     words = chengyu.index[chengyu.shoupin == chengyu.loc[word, "weipin"]]
  27.     if words.shape[0] == 0:
  28.         print("恭喜你赢了!成语机器人已经被你打败!!!")
  29.         break
  30.     word2 = np.random.choice(words)
  31.     print(word2)
  32.     weipin = chengyu.loc[word2, "weipin"]

  1. 是否先手(输入N表示后手,其他表示先手)
  2. 请输入一个成语(认输或离开请按Q):妙趣横生
  3. 生米煮成熟饭
  4. 请输入一个成语(认输或离开请按Q):饭来开口
  5. 口呆目钝
  6. 请输入一个成语(认输或离开请按Q):遁名匿迹
  7. 计功谋利

由于成语积累量较少,几局就已经快玩不下去,于是我打算再写个成语查询器方便开挂后再上,而不是疯狂的百度,代码如下:

  1. from gooey import Gooey, GooeyParser
  2. import pandas as pd
  3. chengyu = pd.read_json("idiom.json")
  4. t = chengyu.pinyin.str.split()
  5. chengyu["shoupin"] = t.str[0]
  6. chengyu["weipin"] = t.str[-1]
  7. chengyu = chengyu.set_index("word")[["shoupin""weipin"]]
  8. @Gooey
  9. def main():
  10.     parser = GooeyParser(description="成语接龙查询器 - @小小明")
  11.     parser.add_argument('word', help="被查询的成语")
  12.     args = parser.parse_args()
  13.     word = args.word
  14.     if word not in chengyu.index:
  15.         print("你输入的不是一个成语,请重新输入!")
  16.     else:
  17.         words = chengyu.index[chengyu.shoupin == chengyu.loc[word, "weipin"]]
  18.         if words.shape[0] > 0:
  19.             print("满足条件的成语有:")
  20.             print("、".join(words))
  21.         else:
  22.             print("抱歉,没有找到能够满足条件的成语")
  23.         print("-----" * 10)
  24. if __name__ == '__main__':
  25.     main()

这里我使用了Gooey,需要pip安装:

pip install Gooey

项目地址:https://github.com/chriskiehl/Gooey

体验一把:

点击start后:

要重新开始查询只需点击Edit按钮即可。Gooey支持的组件还挺多的,可以参考GitHub项目说明。虽然Gooey远不如专业的图形化框架专业,但对于简单的需求也挺简单便捷,能快速把命令行程序转换为图形化程序。

参考

《文本数据挖掘——基于R语言》黄天元

---------End---------

精选资料

回复关键词,获取对应的资料:

精选内容

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/91877
推荐阅读
相关标签
  

闽ICP备14008679号