【问题标题】:How to return the sum of the values for a given .csv file?如何返回给定 .csv 文件的值的总和?
【发布时间】:2015-05-17 06:54:23
【问题描述】:

我有一个这样的 .csv 文件,它有单词和值:

string1, 102, 90, 23
string2, 89, 45, 21
...
hi, 1, 3, 5
example, 2, 0, 2
someone, 1, 1, 1
hope, 0, 0, 0
stringN, 923, 23892, 9292
stringnN-1, 2903, 49058, 4859

还有很多这样的单词:

lis__ = [[Hi this is an example, this site is nice!.],...,[I hope someone can help]]

如何返回出现在lis__ 中的每个单词的值的总和。对于上述实例,输出将是这样的:

对于第一个子列表:

    [Hi this is an example, this site is nice!.]

In:
    hi, 1, 3, 5
    example, 2, 0, 2
    someone, 1, 1, 1
    hope, 0, 0, 0

Then add value one with value one, two with two and three with three:

Out:
[(3,3,7)]

然后对于第二个子列表,将值 1 与值 1、2 与 2、3 与 3 相加:

In:
    [I hope someone can help]
    hi, 1, 3, 5
    example, 2, 0, 2
    someone, 1, 1, 1
    hope, 0, 0, 0
out:
    [(1,1,1)]

最后:

[(3,3,7),...,(1,1,1)]

其中... 是无限的字符串或元组。可能这个任务可以用csv 模块来完成,知道如何解决这个问题吗?提前谢谢各位!

【问题讨论】:

    标签: python list python-2.7 parsing csv


    【解决方案1】:

    怎么样:

    import csv
    import re
    
    class Score(object):
        def __init__(self, *args):
            self.lst = args
    
        def __repr__(self):
            return str(tuple(self.lst))
    
        def __iadd__(self, other):
            new = [self.lst[i] + other.lst[i] for i in range(3)]
            return Score(*new)
    
    
    lis__ = [
        'Hi this is an example, this site is nice!.',
        'I hope someone can help',
    ]
    
    # Build word_scores dictionary, keyed by word
    word_scores = {}
    with open('yourcsv.csv') as f:
        reader = csv.reader(f)
        for line in reader:
            word_scores[line[0].lower()] = Score(*map(int, line[1:]))
    
    
    # Loop over lis__, computing the total score for each element (elem_score),
    #    append it to line_scores
    line_scores = []
    for elem in lis__:
        elem_score = Score(0,0,0)
        for word in re.split(r'[^\w]+', elem):
            try:
                score = word_scores[word.lower()]
                print("  Found: %s %s" % (word.lower(), score))
                elem_score += score
            except KeyError:
                pass
        print("%s : %s" % (elem_score, elem))
        line_scores.append(elem_score)
    
    print
    print "Line Scores:"
    print line_scores
    

    输出:

    找到:hi (1, 3, 5) 找到:示例 (2, 0, 2) (3, 3, 7) : 嗨,这是一个例子,这个网站很好! 找到:希望 (0, 0, 0) 找到:某人 (1, 1, 1) (1, 1, 1) : 我希望有人能帮忙 线分数: [(3, 3, 7), (1, 1, 1)]

    【讨论】:

    • 尝试将Score(*map(int, line[1:]))更改为Score(*map(float, line[1:]))Score(*map(lambda x: int(float(x)), line[1:]))
    • 当然很抱歉,我刚刚意识到浮动。非常感谢你的帮助。我想看看总和是多少。
    • lis__ 应该如下所示:lis__ = [ ['Hi this is an example, this site is nice!.'], ['I hope someone can help'] ] 而不是一个列表。是列表的列表。知道如何进行吗?。
    • 如果所有子列表都是单个元素,将for word in re.split(r'[^\w]+', elem):改为for word in re.split(r'[^\w]+', elem[0]):
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2019-05-08
    • 2014-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多