首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何过滤python中的csv

如何过滤python中的csv
EN

Stack Overflow用户
提问于 2022-11-24 14:06:22
回答 2查看 48关注 0票数 2

我有一个名为film.csv的csv文件,每个列的标题如下(有几行示例):

代码语言:javascript
复制
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

我需要使用基本命令解析这个csv (不使用Pandas)

  1. ,我如何提取所有的电影标题与演员的名字=理查德,在1985年之前,并奖=是?(我已经让它向lisy展示了==是的,但没有其他的)

  1. ,我怎么能算出一个演员在名单中出现了多少次?

代码语言:javascript
复制
file_name = "film.csv"
print('loading file')
lines = (line for line in open(file_name,encoding='cp1252')) #generator to capture lines
print('removing ;')
lists = (s.rstrip().split(";") for s in lines) #generators to capture lists containing values from lines

print('2-filter by awards')
sel = input()

if sel == '2': 
cols=next(lists) #obtains only the header
    print(cols)
    collections = (dict(zip(cols,data)) for data in lists)
    
    filtered = (col["Title"] for col in collections if col["Awards"][0]== "Y")
    for item in filtered:
        print(item)
    #   input()

        
#browse lists and index them per header values, then filter all movies that have been awarded
#using a new generator object
else: 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-11-24 14:42:54

这将打印出所有电影标题,演员的名字是理查德,在1985年之前制作,并授予==是的:

代码语言:javascript
复制
filter = {}
lines = open('test.csv', 'r').readlines()
columns = lines[0].strip().split(';')

lines.pop(0)

for i in lines:
    x = i.strip().split(';')
    # Checking if the movie was made before 1985
    if int(x[columns.index('Year')]) < 1985:
        # Checking if the actor's first name is Richard
        if x[columns.index('Actor')].split(', ')[1] == 'Richard':
            # Checking if awards == Yes
            if x[columns.index('Awards')] == 'Yes':
                # Printing out the title of the movie
                print(x[columns.index('Title')])

如果列表中出现任何给定的参与者,则计数:

代码语言:javascript
复制
name = "Gere, Richard" #   Given actor name

count = 0
for i in lines:
    x = i.strip().split(';')
    # Checking if the actor's name is the given name
    if x[columns.index('Actor')] == name:
        # If it is, add 1 to the count
        count += 1

输出:计数: 1

票数 0
EN

Stack Overflow用户

发布于 2022-11-24 16:59:00

要读取和过滤数据,可以使用下一个示例(我使用的是award == No,因为在示例中没有使用award == Yes和其他条件的电影):

代码语言:javascript
复制
import csv
from collections import Counter

with open("data.csv", "r") as f_in:
    reader = csv.DictReader(f_in, delimiter=";")
    data = list(reader)

# extract all movie titles with the actor first name = Richard , made before year 1985 , and award = No

for d in data:
    if (
        d["Actor"].split(", ")[-1] == "Richard"
        and int(d["Year"]) < 1985
        and d["Awards"] == "No"
    ):
        print(d)

指纹:

代码语言:javascript
复制
{
    "Year": "1978",
    "Length": "94",
    "Title": "Days of Heaven",
    "Subject": "Drama",
    "Actor": "Gere, Richard",
    "Actress": "Adams, Brooke",
    "Director": "Malick, Terrence",
    "Popularity": "14",
    "Awards": "No",
    "*Image": "NicholasCage.png",
}

要获得演员的计数器,可以使用collections.Counter

代码语言:javascript
复制
cnt = Counter(d["Actor"] for d in data)
print(cnt)

指纹:

代码语言:javascript
复制
Counter(
    {
        "Banderas, Antonio": 1,
        "Bosé, Miguel": 1,
        "Walken, Christopher": 1,
        "Connery, Sean": 1,
        "Gere, Richard": 1,
        "Moore, Roger": 1,
    }
)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74562025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档