使用xlwtin Python编写列标题
我正在尝试parsing一些Twitter Streaming API数据并将特定字段写入Excel工作簿中的列。 使用xlwt
,我已经能够将列写入Excel文档,但是我还没有find包含列标题的好方法。
我知道每行要在第1行中标注什么,所以不需要从原始数据中parsing列名。 列1标题应该是“user_screen.name”,列2标题应该是“user_lang”
import sys import json import xlwt data = [] for line in open(sys.argv[1]): try: data.append(json.loads(line)) except: pass authors = [i['user']['screen_name'] for i in data] lang = [i['lang'] for i in data] workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet 1') column_number = 0 for row_number, item in enumerate(authors): worksheet.write(row_number, column_number, item) column_number = 1 for row_number, item in enumerate(lang): worksheet.write(row_number, column_number, item) workbook.save('tweets.xls')
如果你只是想要静态硬编码的头文件,你可以很容易地做到这一点,对你的程序进行微小的调整(见下文):
import sys import json import xlwt data = [] for line in open(sys.argv[1]): try: data.append(json.loads(line)) except: pass authors = [i['user']['screen_name'] for i in data] lang = [i['lang'] for i in data] workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet 1') column_number = 0 worksheet.write(0, column_number, 'Authors') for row_number, item in enumerate(authors): worksheet.write(row_number+1, column_number, item) column_number = 1 worksheet.write(0, column_number, 'Language') for row_number, item in enumerate(lang): worksheet.write(row_number+1, column_number, item) workbook.save('tweets.xls')
注意:我没有能够完全testing没有input文件,但我认为这应该工作。