|  | 
 
| 
准备文档三国演义:sanguoyanyi.txt、weapon.txt
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  weapon.txt的内容如下:
 青龙偃月刀
 
 丈八蛇矛
 
 雌雄双剑
 
 青釭剑
 
 方天画戟
 
 
 复制代码import re
def find_item2(weapon):
    with open('sanguoyanyi.txt', encoding='utf-8') as f1:
        data = f1.read().replace('\n', '')
        weapon_num = len(re.findall(weapon, data))
        print("\033[31:1m%s\033[0m出现了%s 次" % (weapon, weapon_num))
    return weapon_num
weapon_dict = {}
# with语句叫上下文管理器,会自动关闭被调用打开的文件
with open('weapon.txt', encoding='utf-8') as f:
    i = 1
    for line in f:
        if i % 2 == 1:
            weapon_name = line.strip()
            weapon_dict[weapon_name] = find_item2(weapon_name)
        i += 1
weapon_sorted1 = sorted(weapon_dict.items(), key=lambda item: item[1], reverse=True)
print('按次数降序排列:', weapon_sorted1)
weapon_sorted2 = sorted(weapon_dict.items())
print('按武器排列:', weapon_sorted2)
 | 
 |