我有一个包含超过10行和3列的文本文件,如:
Classification Type A B
Commercial Homes 12 15
Residential Homes 10 14
................ .. ..
我想分别阅读每一栏,如:
Classification = ['Commercial Homes', 'Residential Homes'.......]
A = [12,10,....]
B = [15,14,....]
我可以使用split()
并将它们读入单独的列表,但分类名称有多个单词,我必须在列表中捕获全名而不是第一个单词。任何建议都会很有意义。
答案 0 :(得分:3)
只需使用zip()
转置由csv reader对象表示的矩阵:
import csv
with open(fn) as f:
reader=csv.reader(f, delimiter='\t')
a, b, c = zip(*reader)
print a
('Classification Type', 'Commercial Homes', 'Residential Homes')
print b
('A', '12', '10')
print c
('B', '15', '14')
# trim the tuples as you wish, such as b=list(b[1:])...
然后,你可能想要一个带有该元组的第一个值的dict:
data={}
for t in zip(*reader):
data[t[0]]=t[1:]
print data
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}
然后可以将其简化为单一陈述:
data={t[0]:t[1:] for t in zip(*reader)}
# {'A': ('12', '10'), 'B': ('15', '14'), 'Classification Type': ('Commercial Homes', 'Residential Homes')}
答案 1 :(得分:0)
这样的事可能有用:
#!/usr/bin/python
with open('./mydata', 'r') as raw_data:
data = [line.strip().split() for line in raw_data.readlines()]
header = data.pop(0) ## Pop off header, removed from list
a = [record[1] for record in data]
b = [record[2] for record in data]
显然,我们两次遍历列表,一次是a
,另一次是b
。对于小型数据集,这不会造成任何性能问题。
或者我们可以这样做:
#!/usr/bin/python
a = list()
b = list()
with open('./mydata', 'r') as raw_data:
for line in raw_data:
if line.startswith('Classification'):
continue # skip the header line
line = line.strip().split()
a.append(line[1])
b.append(line[2])
这有点冗长。但它只需一次通过数据即可完成工作。
答案 2 :(得分:0)
使用csv库执行任务
import csv
def main():
with open(r'CSVReaderData.txt', 'r') as f:
reader = csv.reader(f, delimiter='\t')
col1, col2, col3 = zip(*reader)
print 'Classification = ',list(col1)
print 'A = ',list(col2)
print 'B = ',list(col3)
if __name__ == '__main__':
main()