文件操作之extract_weapon
准备文档三国演义:sanguoyanyi.txt、weapon.txtweapon.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 = find_item2(weapon_name)
i += 1
weapon_sorted1 = sorted(weapon_dict.items(), key=lambda item: item, reverse=True)
print('按次数降序排列:', weapon_sorted1)
weapon_sorted2 = sorted(weapon_dict.items())
print('按武器排列:', weapon_sorted2)
页:
[1]