我有一个 CSV 字符串,其中包含 GeoJSON 字符串。
str="""LC08,2016-08-02,"{'type':'Polygon','coordinates':[[[10,20],[50,40],[60,80],[15,45 ],[10,20]]]}",-9999,-9999"""
我打算将此字符串压缩到 Python 字典中
我尝试执行常规的拆分和压缩功能,但显然结果不符合预期。由于字符串的格式,分割是一个障碍。
这是我目前拥有的:
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"
}
最佳答案
您(可能)想要的是使用正则表达式进行拆分,更准确地说是使用 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为表达式。
关于python - 将包含 GeoJSON 的 CSV 字符串压缩到 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55785481/