繁体   English   中英

使用列表和for循环在Python列表中处理csv

[英]Processing csv in Python lists using lists and for loops

我正在读取一个csv,并从该csv的前4列中列出了4个列表。

listofcelebs = (columns['name'])
listOfImages = (columns['image'])
listOfProfessions = (columns['profession'])
listOfBestWork = (columns['bestWork'])

我只需要从第一个列表中读取项目,就可以对每个项目进行Twitter情绪分析并打印出结果。 但是,我也想打印出它们之间的其他列表。

我如何打印

名人清单中的第一项,

然后是列表listOfImages的第一项,

然后是列表listOfProfessions的第一项,

然后是列表listOfBestWork的第一项,

然后是名人列表list的第一项的Twitter情绪分析结果,

喷雾器 “------------------------------------------------- -------------------- \\ n“

然后是名人列表中的第二项,

然后是列表listOfImages的第一项,

等等等

最后,我将结果存储在标题为[名称,图像,专业,bestWork,overallSentiment]的新csv中


这是我的代码当前给出了错误的缩进错误

import csv
import twittersearch
from collections import defaultdict

c = csv.writer(open("celebritiesBornTodayWithSentiment.csv", "wb"))
columns = defaultdict(list) # each value in each column is appended to a list

with open('celebritiesBornToday.csv') as f:
    reader = csv.DictReader(f) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value 
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k

listofcelebs = (columns['name'])
listOfImages = (columns['image'])
listOfProfessions = (columns['profession'])
listOfBestWork = (columns['bestWork'])

zippedListofCelebInfo = zip(listOfNames, listOfImages, listOfProfessions, listOfBestWork)

#giving headings to the columns of the final csv file
c.writerow(['name','image','profession','bestWork','overallSentiment'])


for name in zippedListofCelebInfo:
    #Printing the Name of the Celebrity
    print "Name of the celebrity: "+name

    #Printing the Image of the Celebrity
    print "Image: "+image

    #Printing the Profession of the Celebrity
    print "Profession: "+profession

    #Printing the BestWork of the Celebrity
    print "BestWork: "+bestWork

    #calling twittersearch2 from the other file to derive tweet sentiment, celebrity's full name used as the query
    overallSentiment = twittersearch.twittersearch2(name)
    print "Overall Sentiment on Twitter : "+overallSentiment

     # End of Celebrity Details
    print "--------------------------------------------------------------------- \n  "

    #saving the name, image, profession, bestWork, overallSentiment of the celebrity into a csv file
    c.writerow([name,image,profession,bestWork,overallSentiment])

如果您确定列表的长度相同,则可以使用zip函数,或者对于较长的列表,最好使用itertools.izip将列表压缩在一起:

from itertools import izip

my_lists=[listofcelebs,listOfImages ,listOfProfessions ,listOfBestWork]
for i,j,k,z in izip(*my_lists):
   print (i,j,k,z)
   print "--------------------------------------------------------------------- \n "

对于小清单:

my_lists=[listofcelebs,listOfImages ,listOfProfessions ,listOfBestWork]
for i,j,k,z in zip(*my_lists):
   print (i,j,k,z)
   print "--------------------------------------------------------------------- \n "

如果要在每一行中打印:

my_lists=[listofcelebs,listOfImages ,listOfProfessions ,listOfBestWork]
for i,j,k,z in zip(*my_lists):
   print i,'\n',j,'\n',k,'\n',z,'\n'
   print "--------------------------------------------------------------------- \n "

正如我所评论的,您已经准备好遍历输入文件的每一行,因此在读取新行(带有附加数据项)后立即将其写入输出,而不是将所有数据存储在其中可能是有意义的。一堆清单:

import csv
import twittersearch

with open('celebritiesBornToday.csv', "rb") as in_f:
    reader = csv.DictReader(in_f)
    with open("celebritiesBornTodayWithSentiment.csv", "wb") as out_f:
        writer = csv.DictWriter(out_f, reader.fieldnames + ["overallSentiment"])
        for row in reader:
            row["overallSentiment"] = twittersearch.twittersearch2(row["name"])
            writer.writerow(row)

            print "Name of the celebrity:", row["name"]
            print "Image:", row["image"]
            print "Profession: ", row["profession"]
            print "BestWork:", row["bestWork"]
            print "Overall Sentiment on Twitter:", row["overallSentiment"]

比您当前的代码要短得多而且简单得多!

暂无
暂无

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

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