我从配置文件中获取各种数据类型并将它们添加到字典中。但我对列表有疑问。我想取一行 text:alist = [1,2,3,4,5,6,7]
并转换为整数列表。但我越来越
['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7'].
我怎样才能解决这个问题?
这是config.txt:
firstname="Joe"
lastname="Bloggs"
employeeId=715
type="ios"
push-token="12345"
time-stamp="Mon, 22 Jul 2013 18:45:58 GMT"
api-version="1"
phone="1010"
level=7
mylist=[1,2,3,4,5,6,7]
这是我要解析的代码:
mapper = {}
def massage_type(s):
if s.startswith('"'):
return s[1:-1]
elif s.startswith('['):
return list(s[1:-1]) #in this case get 'mylist': ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7']
elif s.startswith('{'):
return "object" #todo
else:
return int(s)
doc = open('config.txt')
for line in doc:
line = line.strip()
tokens = line.split('=')
if len(tokens) == 2:
formatted = massage_type(tokens[1])
mapper[tokens[0]] = formatted
#check integer list
mapper["properlist"] = [1,2,3,4,5,6,7] #this one works
print mapper
这是我的打印输出:
{'time-stamp': 'Mon, 22 Jul 2013 18:45:58 GMT', 'mylist': ['1', ',', '2', ',', '3', ',', '4', ',', '5', ',', '6', ',', '7'], 'employeeId': 715, 'firstname': 'Joe', 'level': 7, 'properlist': [1, 2, 3, 4, 5, 6, 7], 'lastname': 'Bloggs', 'phone': '1010', 'push-token': '12345', 'api-version': '1', 'type': 'ios'}
更新。
感谢您的反馈。我意识到我也可以获得异构列表,因此将列表部分更改为:
elif s.startswith('['):
#check element type
elements = s[1:-1].split(',')
tmplist = [] #assemble temp list
for elem in elements:
if elem.startswith('"'):
tmplist.append(elem[1:-1])
else:
tmplist.append(int(elem))
return tmplist
它只处理字符串和整数,但足以满足我现在的需要。