【问题标题】:How to count items in csv file python?如何计算csv文件python中的项目?
【发布时间】:2017-11-15 17:43:10
【问题描述】:

我正在使用 kaggle imdb 5000 数据集,您可以查看详细信息 here。 我正在尝试使新的 csv 文件看起来像 。 但是流派行也必须拆分。

流派行:
[{"id": 28, "name": "Action"}, {"id": 12, "name": "Adventure"}, {"id": 14, "name": "Fantasy"}, { "id": 878, "name": "科幻小说"}]

如何在流派行中获取名称属性?

with open(filename) as myFile:  
    reader = csv.DictReader(myFile)
    for row in reader:
        print(row['genres'].'name')

print(row['genres'].'name') 不起作用。

【问题讨论】:

  • 我不明白,您为什么希望 r['genres'].'name' 起作用,您希望它做什么?
  • 该列包含 JSON,因为您链接的页面提到您应该解析 JSON。
  • @juanpa.arrivillaga 实际上,我不希望它起作用,我正试图摆脱除电影名称、流派和概述之外的所有数据。但在流派列中,除了流派名称之外,还有更多信息。
  • @alexisdevarennes 请不要要求勾选,除非提问者已经表明您的答案是正确的(并且您认为他们只是不知道他们应该这样做)。见meta。
  • @glibdud 作为您链接到状态的帖子中的其他用户,请新用户检查答案是完全可以的。不幸的是,大多数 SO 上的新用户并没有这样做,建议他们这样做并且留下友好的提醒并不要求恕我直言。

标签: python csv


【解决方案1】:

更仔细地查看您自己的示例: 你有一个包含两个键的字典列表:它们不是嵌套的。

{"id": 28, "name": "Action"}

row['genres'].'name' 的语法和您正在尝试做的事情是错误的:

row['genres']['name'] 表示:{"id": { "name": "Action"} }

所以尝试使用名称属性,例如:

print(row['genres'], row['name'])

有关一个简洁的示例,另请参阅文档:https://docs.python.org/2/library/csv.html#csv.DictReader

【讨论】:

    【解决方案2】:
    import json
    with open(filename) as myFile:  
        reader = csv.DictReader(myFile)
        for row in reader:
            if not isinstance(row, dict):  # The row might be a string, in that case, parse it to a dict.
                row = json.loads(row)  # Parse the json row and convert it to dict.
            print([o['name'] for o in row])  # Iterate over every entry in the row and access the value 'name', will return a list of genre names.
    
            print(', '.join([o['name'] for o in row]))  # Will return a string of comma separated genre names.
    
            print([{'name': o['name']} for o in row])  # Will return a list of Genre objects, deleting all keys but 'name'
    

    【讨论】:

    • 我试图运行您的解决方案,但我收到错误消息“TypeError:字符串索引必须是整数,而不是 str。”但我明白你的意思是我做错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2019-04-04
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2021-02-13
    相关资源
    最近更新 更多