此问题不是同一问题的重复,但与某些功能匹配。我的问题是我也想将几个单元格也转换成列表,但是在这个问题中没有提到
数据为文本:
11916,testBuild,Test Building,Udaipur sector-5 Hiran Magri,181,753180 794950,"1,2",UC,2018-08-22,"2BHK, 3BHK"
这是我的不含标题的csv列
我正在尝试阅读并将其转换为逗号分隔的列表,以便可以分别访问每个元素
下面是我的代码:
def Residential():
global url, parse_url
filename = "Residential.csv"
f = open(filename, "r")
for line in f.readlines():
data = line.split(",")
builderid = data[0]
print(builderid)
buildername = data[1]
print(buildername)
buildingname = data[2]
print(buildername)
address = data[3]
city = data[4]
locality = data[5]
building_id = data[6]
apartment = data[7].replace("\"","")
print(type(apartment))
status = data[8].replace("\"","")
print(status)
cdate = data[9]
bhk = data[10]
rnumber = data[11]
rurl = data[12]
print(data)
Residential()
属于属性类型和bhk的元素7和10也被","
分隔开了,我怎么不用逗号分隔它们并将元素7照原样读入列表和元素10中。
喜欢这个,我想读
['11916', 'testBuild', 'Test Building', 'Udaipur sector-5 Hiran Magri',
'181', '753180', '794950', **[1,2]**, 'UC', '2018-08-22', **"2BHK, 3BHK"**,
'', '\n']
这是我收到的结果:
['11916', 'testBuild', 'Test Building', 'Udaipur sector-5 Hiran
Magri', '181', '753180', '794950', '"1', '2"', 'UC', '2018-08-22',
'"2BHK', ' 3BHK"', '', '\n']
答案 0 :(得分:2)
Python中有一个CSV解析器,可以正确处理包含逗号的带引号的字符串:
(假设filename.csv仅包含一行,如您在问题中所发布的那样)
import csv
with open('filename.csv') as f:
reader = csv.reader(f)
for row in reader:
row[6] = list(map(int, row[6].split(",")))
print(row)
给出结果
['11916', 'testBuild', 'Test Building', 'Udaipur sector-5 Hiran Magri', '181', '753180 794950', [1,2], 'UC', '2018-08-22', '2BHK, 3BHK']
答案 1 :(得分:1)
您只需要使用json
模块。
import json
s = '1,"2,3","123,234"' # one line of your csv for example
s = '[{}]'.format(s)
data = json.loads(s) # data is a list now
print data