从URL获取CSV文件并将其转换为数组-Python 2.7
我正在尝试获取地震数据,并将其转换为一个数组,以便我可以使用该数据在地图上可视化地震。我正在写这个脚本:从URL获取CSV文件并将其转换为数组-Python 2.7,python,arrays,csv,Python,Arrays,Csv,我正在尝试获取地震数据,并将其转换为一个数组,以便我可以使用该数据在地图上可视化地震。我正在写这个脚本: import requests import csv def csv_to_array(a): b = requests.get(a) my_file = open(b, "rb") for line in my_file: el = [i.strip() for i in line.split(',')] return el 我
import requests
import csv
def csv_to_array(a):
b = requests.get(a)
my_file = open(b, "rb")
for line in my_file:
el = [i.strip() for i in line.split(',')]
return el
我将其导入另一个模块,并且:
import csvToArray
data = csvToArray.csv_to_array(
"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.csv")
i = 1
while i < len(data):
stuff = data[i].split(',')
print stuff[1], stuff[2]
lat = float(stuff[1])
lon = float(stuff[2])
x = webMercX(lon, zoom) - cx
y = webMercY(lat, zoom) - cy
i += 1
导入csvToArray
data=csvToArray.csv_到_数组(
"http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.csv")
i=1
而i
上面脚本的其他函数是不必要的,但是当我运行它时,我得到以下错误
while i < len(data):
TypeError: object of type 'NoneType' has no len()
而i
您可以使用生成器替换第一个函数,该生成器迭代响应数据并为文件的每一行生成数组
def csv_to_array(a):
response = requests.get(a)
# you can access response's body via text attribute
for line in response.text.split('\n'):
yield [i.strip() for i in line.split(',')]
list(csv_to_array(some_url))
大多数建议都是代码中的注释,但也有一些一般性建议:
yield
可以生成一行又一行def csv_to_array(url): # use descriptive variable names
response = requests.get(url)
lines = response.text.splitlines() # you don't need an open...the data is already loaded
for line in lines[1:]: # skip first line (has headers)
el = [i.strip() for i in line.split(',')]
yield el # don't return, that immediately ends the function
data = csv_to_array("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.csv")
for row in data: # don't use indexes, just iterate over the data
# you already split on commas.
print(row[1], row[2]) # again, better names
lat = float(row[1])
lon = float(row[2])
# x = webMercX(lon, zoom) - cx
# y = webMercY(lat, zoom) - cy
懒惰者的代码:
import pandas as pd
pd.read_csv('http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_hour.csv')
因为
print
不返回任何内容:),所以您没有从csv\u返回任何内容到\u数组
Wow,这是一个愚蠢的错误(我刚刚修复了),但现在我得到了以下错误:my\u file=open(b,“rb”)TypeError:强制使用Unicode:需要字符串或缓冲区,响应发现它没有将URL识别为字符串。现在您只返回文件的第一行。函数在第一次返回时立即结束
对于在谷歌地图上绘图,我要看看gmplot。