繁体   English   中英

如何读取多个 .csv 文件并分析数据?

[英]How to read multiple .csv files and analyse the data?

以下情况:

  • 电影.csv

    movieId,title,genres

  • 标签.csv

    userId,movieId,tag,timestamp

我想从 tags.csv 获取标签并附加到包含应存储所有标签的列表的字典中。 movieID 应该相同,以便可以附加列表。 该列表也不应该有重复项。

这是代码:

import csv
reader = csv.reader(open('movies1.csv'))

dict = {}
header = next(reader)
# Check file as empty
if header != None:
    for row in reader:
        key = row[0]
        value = {
        "id": row[0],
        "title": row[1][:-6],
        "year": row[1][-5:-1],
        "average_rating": 0,
        "ratings": [],
        "tags": [], #the list that should be filled with tags
        "genres": row[2].split('|')
        }
        dict[key] = value
tags={}
with open('tags1.csv', mode='r') as infile:
    reader = csv.reader(infile)
    header = next(reader)
    # Check file as empty
    if header != None:
        for col in reader:
            if col[1] == dict[key]['id']:
                dict[key]['tags'].append(col[2])


    print(dict)

我的结果:

我得到了上一部电影的所有标签。 其余的标签只是空的。 我究竟做错了什么?

所以我让它工作。 我创建了第二个字典,并在它们两个中循环。

for tag in tags:
    for movie in dict:

        if tags[tag]['movieId'] == dict[movie]['id']:
            if tags[tag]['tag'] not in dict[movie]['tags']:
                dict[movie]['tags'].append(tags[tag]['tag'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM