You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用基础Python命令处理film.csv:筛选电影与统计演员频次

基于基础Python解析CSV文件的解决方案

需求说明

使用纯基础Python(不依赖Pandas)解析film.csv文件,完成两个任务:

  • 提取**演员名字包含Richard、上映年份早于1985且获奖(Awards=Yes)**的所有电影标题
  • 统计任意指定演员在列表中的出现次数

示例CSV文件(film.csv)

Year;Length;Title;Subject;Actor;Actress;Director;Popularity;Awards;*Image
1990;111;Tie Me Up! Tie Me Down!;Comedy;Banderas, Antonio;Abril, Victoria;Almodóvar, Pedro;68;No;NicholasCage.png
1991;113;High Heels;Comedy;Bosé, Miguel;Abril, Victoria;Almodóvar, Pedro;68;No;NicholasCage.png
1983;104;Dead Zone, The;Horror;Walken, Christopher;Adams, Brooke;Cronenberg, David;79;No;NicholasCage.png
1979;122;Cuba;Action;Connery, Sean;Adams, Brooke;Lester, Richard;6;No;seanConnery.png
1978;94;Days of Heaven;Drama;Gere, Richard;Adams, Brooke;Malick, Terrence;14;No;NicholasCage.png
1983;140;Octopussy;Action;Moore, Roger;Adams, Maud;Glen, John;68;No;NicholasCage.png

补全后的完整代码

file_name = "film.csv"
print('加载文件中')
# 生成器读取文件行,节省内存
lines = (line for line in open(file_name, encoding='cp1252'))
print('分割字段中')
# 修复原代码语法错误,生成器处理每行并分割为字段列表
lists = (s.rstrip().split(";") for s in lines)

print("请选择操作:")
print("1 - 提取符合条件的电影标题")
print("2 - 统计指定演员出现次数")
sel = input("输入选项编号:")

# 获取表头行,生成字典格式的数据生成器
cols = next(lists)
collections = (dict(zip(cols, data)) for data in lists)

if sel == '1':
    # 多条件筛选:演员含Richard、年份<1985、获奖为Yes
    filtered_titles = (
        col["Title"] for col in collections
        if "Richard" in col["Actor"] 
        and int(col["Year"]) < 1985 
        and col["Awards"].strip().lower() == "yes"
    )
    print("\n符合条件的电影标题:")
    for title in filtered_titles:
        print(title)
elif sel == '2':
    target_actor = input("\n请输入要统计的演员名字:")
    # 统一转为小写避免大小写匹配误差,统计演员在所有相关字段中的出现次数
    count = 0
    target_lower = target_actor.strip().lower()
    for col in collections:
        if target_lower in col["Actor"].lower():
            count += 1
        if target_lower in col["Actress"].lower():
            count += 1
        if target_lower in col["Director"].lower():
            count += 1
    print(f"\n演员{target_actor}共出现{count}次")
else:
    print("\n无效选项,请重新运行程序选择1或2")

代码说明

  1. 修复了原代码中lists生成器的语法错误(多嵌套了一层括号)
  2. 任务1的筛选逻辑:同时校验三个条件,年份字段转为整数后比较,获奖字段做大小写不敏感处理
  3. 任务2的统计逻辑:支持在演员、女演员、导演字段中匹配目标演员,同样做了大小写和空格兼容处理,避免输入差异导致统计偏差

内容的提问来源于stack exchange,提问作者Tristan Houghton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:35:24