文件操作之extract_name
准备文档三国演义:sanguoyanyi.txt、name.txt
name.txt的内容如下:诸葛亮|关羽|张飞|刘备|曹操|孙权|周瑜|庞统|赵云|吕布
练习:提取相关人物,并统计出现的次数,然后排序
import re
def find_item(hero):
with open('sanguoyanyi.txt', encoding='utf-8') as f:
data = f.read().replace('\n', '')
name_num = re.findall(hero, data)
print('\033[31:1m%s\033[0m' % hero, len(name_num), '次')
# print语句用来检测运行效果,开始没有用len函数,发现没有统计次数,而是出现一次就赋值添加一次
# 所以后来使用len(name_num)函数来计数
return len(name_num)
names_dict = {}
with open('name.txt', encoding='utf-8') as f:
for line in f:
names = line.split('|')
for n in names:
name_num = find_item(n)
names_dict = name_num
names_sorted1 = sorted(names_dict.items(), key=lambda item: item, reverse=True)
print('按次数降序排列:', names_sorted1)
names_sorted2 = sorted(names_dict.items())
print('按姓名排列:', names_sorted2)
页:
[1]