鱼C论坛

 找回密码
 立即注册
查看: 3192|回复: 0

[技术交流] 文件操作之extract_weapon

[复制链接]
发表于 2020-9-25 09:05:55 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
准备文档三国演义:sanguoyanyi.txt、weapon.txt
weapon.txt的内容如下:
青龙偃月刀

丈八蛇矛

雌雄双剑

青釭剑

方天画戟

  1. import re


  2. def find_item2(weapon):
  3.     with open('sanguoyanyi.txt', encoding='utf-8') as f1:
  4.         data = f1.read().replace('\n', '')
  5.         weapon_num = len(re.findall(weapon, data))
  6.         print("\033[31:1m%s\033[0m出现了%s 次" % (weapon, weapon_num))
  7.     return weapon_num


  8. weapon_dict = {}
  9. # with语句叫上下文管理器,会自动关闭被调用打开的文件
  10. with open('weapon.txt', encoding='utf-8') as f:
  11.     i = 1
  12.     for line in f:
  13.         if i % 2 == 1:
  14.             weapon_name = line.strip()
  15.             weapon_dict[weapon_name] = find_item2(weapon_name)
  16.         i += 1
  17. weapon_sorted1 = sorted(weapon_dict.items(), key=lambda item: item[1], reverse=True)
  18. print('按次数降序排列:', weapon_sorted1)
  19. weapon_sorted2 = sorted(weapon_dict.items())
  20. print('按武器排列:', weapon_sorted2)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 14:46

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表