【发布时间】:2014-07-20 15:15:58
【问题描述】:
我需要帮助来完成这个 python 脚本。我是一家公司的实习生,这是我的第一周。我被要求开发一个 python 脚本,它将采用 .csv 并将任何相关列放入(附加)到一列中,以便它们只有 15 个左右的必要列,其中包含数据。例如,如果有 zip4、zip5 或邮政编码列,他们希望这些都位于邮政编码列的下方。
我这周刚开始学习 python,因为我正在做这个项目,所以请原谅我的菜鸟问题和词汇。我不是在找你们为我做这件事。我只是在寻找一些指导。事实上,我想了解更多关于python的信息,所以任何可以引导我走向正确方向的人,请帮助。
我正在使用字典键和值。键是第一行中的每一列。每个键的值是剩余的行(第二到 3000 行)。现在,我只得到一个键:值对。我只得到最后一行作为我的值数组,而且我只得到一个键。另外,我收到一条 KeyError 消息,所以我的密钥没有被正确识别。到目前为止,我的代码在下面。我会继续努力,非常感谢任何帮助!希望我可以通过帮我喝啤酒的人,我可以稍微了解一下他们的大脑:)
感谢您的宝贵时间
# To be able to read csv formated files, we will frist have to import the csv module
import csv
# cols = line.split(',')# each column is split by a comma
#read the file
CSVreader = csv.reader(open('N:/Individual Files/Jerry/2013 customer list qc, cr, db, gb 9-19-2013_JerrysMessingWithVersion.csv', 'rb'), delimiter=',', quotechar='"')
# define open dictionary
SLSDictionary={}# no empty dictionary. Need column names to compare to.
i=0
#top row are your keys. All other rows are your values
#adjust loop
for row in CSVreader:
# mulitple loops needed here
if i == 0:
key = row[i]
else:
[values] = [row[1:]]
SLSDictionary = dict({key: [values]}) # Dictionary is keys and array of values
i=i+1
#print Dictionary to check errors and make sure dictionary is filled with keys and values
print SLSDictionary
# SLSDictionary has key of zip/phone plus any characters
#SLSDictionary.has_key('zip.+')
SLSDictionary.has_key('phone.+')
#value of key are set equal to x. Values of that column set equal to x
#[x]=value
#IF SLSDictionary has the key of zip plus any characters, move values to zip key
#if true:
# SLSDictionary['zip'].append([x])
#SLSDictionary['phone_home'].append([value]) # I need to append the values of the specific column, not all columns
#move key's values to correct, corresponding key
SLSDictionary['phone_home'].append(SLSDictionary[has_key('phone.+')])#Append the values of the key/column 'phone plus characters' to phone_home key/column in SLSDictionary
#if false:
# print ''
# go to next key
SLSDictionary.has_value('')
if true:
print 'Error: No data in column'
# if there's no data in rows 1-?. Delete column
#if value <= 0:
# del column
print SLSDictionary
【问题讨论】:
-
您不只是使用 csv.DictReader 有什么原因吗?
-
我应该使用 csv.DictReader 而不是 csv.reader?
标签: python csv dictionary key