【问题标题】:Matching values from multiple txt files in Python在 Python 中匹配来自多个 txt 文件的值
【发布时间】:2018-05-03 01:59:34
【问题描述】:

我有 2 个 txt 文件,我需要从 fileA 中获取一个值,将其与 fileB 匹配并打印结果。

fileA 包含用户 ID、艺术家 ID 以及艺术家 ID 已播放的次数。 fileB 包含艺术家 ID 和艺术家的姓名。

我需要编写一个函数来告诉我某个用户播放了某位艺术家的次数。我需要打印艺术家的名字和次数。我完成了伪代码,但无法继续前进。

def printListenersTimesPlayed(userID)
    find all artists and number of time they've been played from fileA
    find the name of the artist from fileB
    print list of artists and times that the user (userID) has played

感谢任何帮助!

【问题讨论】:

    标签: python text match extract


    【解决方案1】:

    我附上完整的代码以及我的示例文件供您参考。请检查它是否解决了您的问题。

    import sys

    import csv

    mapFileA=sys.argv[1]

    mapFileB=sys.argv[2]

    Artist_dict ={}

    data_dict ={}

    with open(mapFileB,'rb') as csvfile: data = csv.reader(csvfile,delimiter=',') for l in data: Artist_dict[l[0]]=l[1] with open(mapFileA,'rb') as csvfile: data = csv.reader(csvfile,delimiter=',') for l in data: if(l[1] in Artist_dict): data_dict[l[0]]=(Artist_dict[l[1]],l[2])

    ## function declaration def findartist(userId): if (userId in data_dict): artist,times=data_dict[userId] print("user "+userId+" played artist "+artist+" "+times+"times") ## function call findartist("100A")

    示例文件: 文件 A - 它包含 user_id、Artist_Id、no。用户播放艺术家的次数

    100A,AAA,10 100B,BBB,3 100C,CCC,50 100D,DDD,7 文件 B:它有 Artist_id、Artist_Name

    AAA,ArtistA BBB,ArtistB CCC,ArtistC DDD,ArtistD 希望它能解决你的问题。

    【讨论】:

    • 谢谢,但我不能使用 sys 或 csv。只有 numpy :/
    猜你喜欢
    • 1970-01-01
    • 2020-07-20
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多