我有一个csv,我正在阅读,并从该csv的前4列4个列表。你知道吗
listofcelebs = (columns['name'])
listOfImages = (columns['image'])
listOfProfessions = (columns['profession'])
listOfBestWork = (columns['bestWork'])
我只需要阅读第一个列表中的条目就可以对每个条目进行twitter情绪分析并打印出结果。不过,我想打印出其他名单之间以及。你知道吗
我怎么打印出来
目录的第一项
然后是图像列表的第一项
然后是职业列表的第一项
然后是第一项工作清单
然后,twitter情绪分析的结果在第一个列表项上
一个说话者,即“----------------------------------------------------\n”
然后是第二项
然后是图像列表的第一项
等等等等
最后,我将结果存储在一个新的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
函数,对于长列表,可以使用^{对于小名单:
如果要在每行中打印:
正如我所评论的,您已经准备好迭代输入文件的每一行了,因此在读取输出后立即将新行(带有附加数据项)写入输出,而不是将所有数据存储在一堆列表中可能是有意义的:
这比你现在的代码要短得多,也简单得多!你知道吗
相关问题 更多 >
编程相关推荐