python,导入csv文件,读取列和行,删除空格,将字符串转换为实数

时间:2017-02-23 20:21:34

标签: whitespace typeconverter

我在将csv文件导入python并将其分开时遇到了问题。我还要删除所有空格并将数字(现在是字符串)转换为整数。这是我到目前为止所拥有的。这些行有效但无法完成删除空格并将字符串转换为整数的任务。

filename = 'myfile.csv'
f = open(filename, 'r')
read = f.readlines()

print(read)

for i in range(len(read)):
    read[i] = read[i].split(',')
print(read)
header = read[0]
print(header)

info = {}
cntr = 0
for name in header:
    info[name] = [line[cntr] for line in read]
    cntr += 1
print(info)

我在这个论坛上搜索过去的例子,这是我试图删除空格但现在我丢失了:

import csv
aList = []
with open('myfile.csv', 'r') as f:
    reader = csv.reader(f, skipinitialspace = True, delimiter = ',', quoting = csv.QUOTE_NONE)
    for row in reader:
        aList.append(row)
    print(aList) 

info = {}
cntr = 0
for i in aList:
    info[aList] = [line[cntr] for line in reader]
    cntr += 1

打印(信息)

1 个答案:

答案 0 :(得分:0)

#sample input
#1 23,456,789
#11 2,11 3,114


import csv
aList = []
with open('myfile.csv', 'r') as f:
    reader = csv.reader(f, skipinitialspace = True, delimiter = ',', quoting = csv.QUOTE_NONE)
    for row in reader:
        aList.append(row)
    print(aList)

info = {}
cntr = 0
print [map(int,[j.replace(" ","") for j in i]) for i in aList]
#[[123,456,789][112,113,114]]

解释 - 使最后一行简单,并分成几部分,

#[i for i in aList] gives [["1 23","456","789"]["11 2","11 3","114"]]
#[j.replace(" ","") for j in i] gives [["123","456","789"]["112","113","114"]]

#[map(int,[j.replace(" ","") for j in i]) for i in aList] 
#maps all string in list to int and gives [[123,456,789][112,113,114]]