import openpyxl import matplotlib.pyplot as plt movie_dict = {} with open('D:\\pythonProject1\\电影信息.txt', 'r',encoding='utf-8') as f: for line in f.readlines(): line = line.strip() movie_info = line.split(';') movie_name = movie_info[0] directors = movie_info[1].split(',') actors = movie_info[2].split(',') for director in directors: if director not in movie_dict: movie_dict[director] = {'movies': [movie_name], 'actors': {}} else: movie_dict[director]['movies'].append(movie_name) for actor in actors: for director in directors: if actor not in movie_dict[director]['actors']: movie_dict[director]['actors'][actor] = 1 else: movie_dict[director]['actors'][actor] += 1 wb = openpyxl.load_workbook('D:\\pythonProject1\\电影信息统计.xlsx') ws = wb.create_sheet('导演作品统计',0) ws.title = '导演作品统计' ws.cell(row=1, column=1, value='导演姓名') ws.cell(row=1, column=2, value='执导电影数量') ws.cell(row=1, column=3, value='执导电影列表') row_num = 2 for director, data in movie_dict.items(): movie_list = ','.join(data['movies']) movie_count = len(data['movies']) ws.cell(row=row_num, column=1, value=director) ws.cell(row=row_num, column=2, value=movie_count) ws.cell(row=row_num, column=3, value=movie_list) row_num += 1 wb.save('D:\\pythonProject1\\电影信息统计.xlsx') director_list = [] movie_count_list = [] for director, data in sorted(movie_dict.items(), key=lambda x: len(x[1]['movies']), reverse=True): director_list.append(director) movie_count_list.append(len(data['movies'])) plt.rcParams['font.family'] = 'sans-serif' plt.rcParams['font.sans-serif'] = ['SimHei'] fig, ax = plt.subplots() ax.barh(director_list, movie_count_list) for i, director in enumerate(director_list): max_actor = [] for actor in movie_dict[director]['actors'].keys(): if movie_dict[director]['actors'][actor]==max(movie_dict[director]['actors'].values()): max_actor.append(actor) max_actor = str(max_actor) max_actor = max_actor.rstrip(']') max_actor = max_actor.lstrip('[') ax.annotate(max_actor, xy=(movie_count_list[i], i), xytext=(movie_count_list[i]+1, i), ha='left', va='center') ax.set_xlabel('执导电影数量') ax.set_ylabel('导演姓名') ax.invert_yaxis() plt.show()请帮我解释一下上述代码,详细一点
时间: 2024-02-07 16:02:31 浏览: 163
这段代码主要是对一个电影信息的文本文件进行处理,统计每个导演执导的电影数量和电影列表,并将结果保存到一个Excel文件中。同时,通过Matplotlib库绘制条形图,展示每个导演执导的电影数量,并在图表上标注每个导演最常用的演员。
具体来说,代码的实现如下:
1. 导入所需的库:
```
import openpyxl
import matplotlib.pyplot as plt
```
其中,openpyxl库用于处理Excel文件,matplotlib.pyplot库用于绘制图表。
2. 定义一个空字典movie_dict,用于存储电影信息:
```
movie_dict = {}
```
3. 打开电影信息的文本文件,逐行读取每条电影信息,将电影名称、导演和演员等信息存储到movie_dict中:
```
with open('D:\\pythonProject1\\电影信息.txt', 'r',encoding='utf-8') as f:
for line in f.readlines():
line = line.strip()
movie_info = line.split(';')
movie_name = movie_info[0]
directors = movie_info[1].split(',')
actors = movie_info[2].split(',')
for director in directors:
if director not in movie_dict:
movie_dict[director] = {'movies': [movie_name], 'actors': {}}
else:
movie_dict[director]['movies'].append(movie_name)
for actor in actors:
for director in directors:
if actor not in movie_dict[director]['actors']:
movie_dict[director]['actors'][actor] = 1
else:
movie_dict[director]['actors'][actor] += 1
```
这段代码使用了文件读写和字符串处理等基本操作。其中,strip()方法用于去除每行字符串两端的空格和换行符;split(';')方法用于将每行字符串按分号分割成电影名称、导演和演员等信息;split(',')方法用于将导演和演员等信息按逗号分割成列表。接着,使用for循环遍历每个导演和演员,将导演执导的电影名称存储到movie_dict中,同时统计每个导演最常用的演员。
4. 打开Excel文件,创建一个新的工作表,将导演执导的电影数量和电影列表写入工作表中:
```
wb = openpyxl.load_workbook('D:\\pythonProject1\\电影信息统计.xlsx')
ws = wb.create_sheet('导演作品统计',0)
ws.title = '导演作品统计'
ws.cell(row=1, column=1, value='导演姓名')
ws.cell(row=1, column=2, value='执导电影数量')
ws.cell(row=1, column=3, value='执导电影列表')
row_num = 2
for director, data in movie_dict.items():
movie_list = ','.join(data['movies'])
movie_count = len(data['movies'])
ws.cell(row=row_num, column=1, value=director)
ws.cell(row=row_num, column=2, value=movie_count)
ws.cell(row=row_num, column=3, value=movie_list)
row_num += 1
wb.save('D:\\pythonProject1\\电影信息统计.xlsx')
```
这段代码使用了openpyxl库中的相关方法,打开了一个已存在的Excel文件,创建了一个新的工作表,并将导演执导的电影数量和电影列表写入工作表中。具体来说,使用create_sheet()方法创建了一个名为“导演作品统计”的工作表,并设置了工作表的标题。然后,使用循环遍历movie_dict中的每个导演,将导演姓名、执导电影数量和电影列表写入工作表中。
5. 统计每个导演执导的电影数量,并使用Matplotlib库绘制条形图:
```
director_list = []
movie_count_list = []
for director, data in sorted(movie_dict.items(), key=lambda x: len(x[1]['movies']), reverse=True):
director_list.append(director)
movie_count_list.append(len(data['movies']))
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['SimHei']
fig, ax = plt.subplots()
ax.barh(director_list, movie_count_list)
for i, director in enumerate(director_list):
max_actor = []
for actor in movie_dict[director]['actors'].keys():
if movie_dict[director]['actors'][actor]==max(movie_dict[director]['actors'].values()):
max_actor.append(actor)
max_actor = str(max_actor)
max_actor = max_actor.rstrip(']')
max_actor = max_actor.lstrip('[')
ax.annotate(max_actor, xy=(movie_count_list[i], i), xytext=(movie_count_list[i]+1, i), ha='left', va='center')
ax.set_xlabel('执导电影数量')
ax.set_ylabel('导演姓名')
ax.invert_yaxis()
plt.show()
```
这段代码使用了Matplotlib库中的相关方法,统计了每个导演执导的电影数量,并使用barh()方法绘制了一个水平条形图。同时,使用annotate()方法在图表上标注了每个导演最常用的演员。最后,设置了x轴和y轴的标签,以及y轴反转等属性,并使用show()方法显示图表。
总体来说,这段代码主要是对电影信息进行处理和分析,并使用Python中的相关库将结果输出到Excel文件和图表中,展示了Python在数据处理和可视化方面的应用。
阅读全文