包含GeoJSON的zip CSV字符串到python字典

时间:2019-04-21 18:19:50

标签: python regex

我有一个包含GeoJSON字符串的CSV字符串。

str="""LC08,2016-08-02,"{'type':'Polygon','coordinates':[[[10,20],[50,40],[60,80],[15,45 ],[10,20]]]}",-9999,-9999"""

我打算将此字符串压缩为Python字典

我尝试执行常规的split和zip函数,但是显然结果与预期的不同。由于字符串的格式,拆分是一个障碍。

这是我目前拥有的:

x="""LC08,2016-08-02,"{'type':'Polygon','coordinates':[[[10,20],[50,40],[60,80],[15,45 ],[10,20]]]}",-9999,-9999"""

values = x.split()
print(values)

row = dict( zip(('name', 'date', 'geometry', 'value0','value1'), values))
print(row)

我还尝试使用以下命令删除引号字符:

values=re.sub('\r\n', '', re.sub(u'"', '', x))
values=values.split()

这并没有真正帮助。

我想要实现的是

{
 name:"LC08", 
 date:"2016-08-02", 
 geometry:"{'type':'Polygon','coordinates':[[[10,20],[50,40],[60,80],[15,45 ],[10,20]]]}",
 value0:"-9999",
 value1:"-9999"
}

1 个答案:

答案 0 :(得分:2)

(可能)您想要的是使用正则表达式进行拆分,更确切地说是使用regex模块进行拆分:

import regex as re

string = """LC08,2016-08-02,"{'type':'Polygon','coordinates':[[[10,20],[50,40],[60,80],[15,45 ],[10,20]]]}",-9999,-9999"""

rx = re.compile(r"""\{[^{}]+\}(*SKIP)(*FAIL)|,""")

d = {}
d['name'], d['date'], d['geometry'], d['value0'], d['value1'] = rx.split(string)
print(d)

哪个产量

{'name': 'LC08', 'date': '2016-08-02', 'geometry': '"{\'type\':\'Polygon\',\'coordinates\':[[[10,20],[50,40],[60,80],[15,45 ],[10,20]]]}"', 'value0': '-9999', 'value1': '-9999'}

有关表达式,请参见a demo on regex101.com