使用Python将列添加到CSV

时间:2015-11-25 19:47:52

标签: python csv field

我有一个CSV文件,如下所示:

id,text,initial_score
1,"Today's news: Democrats offer Republicans everything they asked for; Republicans demand more. Not hard to understand: R's want a shutdown.",0

我想创建一个新文件,其中包含相同的字段并添加一个新字段作为列。新字段将是均衡的结果。我使用以下代码但是存在语法错误:

f1 = open(filepathIntro)
f = open(filepath)
for line in f1:

    cols = split_line(line)
    words1 = get_tweet_words(cols)
    total_score = 0
    for w1 in words1:
        for line in f:
            if not line.startswith("#"):
                cols = split_line(line)
                words2 = get_words(cols)
                for w2 in words2:
                    if w1 == w2:
                        posnum = float(get_positive(cols))
                        negnum = float(get_negative(cols))
                        total_score = total_score + (posnum - negnum)

    with open(filepathIntro, 'r') as f1, open('semevalSenti.csv', 'w+' ) as fout:
        reader = csv.reader(f1)
        writer = csv.writer(fout)
        writer.writerow(next(reader) + ['Total score'])
        writer.writerows([reader] + float(total_score) )

消息错误是:

writer.writerows([a] + total_score for a,total_score  in zip(reader,total_score)) TypeError: zip argument #2 must support iteration
你能帮帮我吗?在此先感谢!!!!!!

1 个答案:

答案 0 :(得分:1)

您错过了writer.writerow(next(reader) + ['Total score'] <-的结束语,也删除了zip(reader, total_score)

的集合文字

我认为writer.writerow(line + total_score)应该是writer.writerow(line + [val]),这意味着一旦定义了writerows并且可迭代的长度相同,您可以使用total_score使用压缩的结果来简化过程作为最初文件中的行数:

with open(filepathIntro, newline='') as f1, open('semevalSenti.csv',newline='', 'w') as fout:
        reader = csv.reader(f1)
        writer = csv.writer(fout)
        writer.writerow(next(reader) + ['Total score'])
        writer.writerows(a + [b] for a,b  in zip(reader, total_score)