【发布时间】:2018-06-08 10:52:41
【问题描述】:
我需要将HTTP 中的字符串写入 CSV 文件。
我的专栏必须是:LATITUDE,LONGITUDE, OSM_ID, HIGHWAY, UPDATED_AT
这是从顶部开始的 HTTP 链接输出示例:
{
"datetime": "2018-06-08T08:26:09.375Z",
"success": true,
"bbox": {
"xmin": "12.335513",
"ymin": "42.035682",
"xmax": "12.758896",
"ymax": "42.050826"
},
"data": [
{
"aggregate_id": 30201274,
"ppe": 0.316954620298806,
"geom": {
"type": "Point",
"coordinates": [
12.532972800901,
42.045435384225
]
},
"osm_id": "37015042",
"highway": "motorway",
"updated_at": "2018-01-20T03:27:11.047Z"
},
{
"aggregate_id": 30201275,
"ppe": 0.318124963244448,
"geom": {
"type": "Point",
"coordinates": [
12.5329908742,
42.045615145535
]
},
"osm_id": "37015042",
"highway": "motorway",
"updated_at": "2018-01-20T03:27:11.047Z"
},
{
"aggregate_id": 30201276,
"ppe": 0.204792151096739,
"geom": {
"type": "Point",
"coordinates": [
12.533008947499,
42.045794906844
]
},
"osm_id": "37015042",
"highway": "motorway",
"updated_at": "2018-01-20T03:27:11.047Z"
},
{
"aggregate_id": 30201277,
"ppe": 0.194797261691664,
"geom": {
"type": "Point",
"coordinates": [
12.533030586679,
42.045974206816
]
},
"osm_id": "37015042",
"highway": "motorway",
"updated_at": "2018-01-20T03:27:11.047Z"
}
]
}
每一行用','分隔。
我写了这段代码
import pandas as pd
import csv
import urllib.request
from urllib.request import urlopen
CSV_URL = 'http://www.smartroadsense.it/bb/12.335513/42.035682/12.758896/42.050826'
request = urllib.request.Request(CSV_URL)
response = urllib.request.urlopen(request)
response.read().decode('utf-8')
#write into csv
colNames = ["longitude","latitude","ppe","osm_id","highway","updated_at"]
data = pd.read_csv(CSV_URL, names=colNames, sep=',')
问题是如何将字符串从 http 拆分成行。有人可以帮助我吗?
【问题讨论】:
-
该问题与
machine-learning无关 - 请不要向标签发送垃圾邮件(已编辑和删除)。 -
它也与请求无关(标签已删除)。
-
您的源字符串格式不是 CSV,而是 JSON。使用
json.load()将其解析为Python dict,然后从该dict 构建你的csv(你不需要panda,stdlib 的csv模块就足够了)。