【问题标题】:Python: How to read file from web and make a list from the data?Python:如何从网络读取文件并从数据中列出?
【发布时间】:2017-08-08 06:11:54
【问题描述】:

所以我完全被困在这里......我有一个我应该使用的 url,我试图读取数据并列出震级为 5 或更大的地震。现在我可以让我的函数打印出数据,但它都打印在几条长线上,而不是每次地震都在它们自己的线上。所以我不确定如何附加幅度值......这是函数和网址:

import urllib.request

def readeqi():

    maglist = [] 

    with urllib.request.urlopen('http://earthquake.usgs.gov/fdsnws/event/1/\
        query?format=csv\
        &starttime=1916-02-01\
        &latitude=44.0519\
        &longitude=-123.0867\
        &maxradiuskm=250\
        &minmagnitude=5') as eq:

        line1 = eq.readline()
        line2 = eq.readline()
        line2 = line2.decode()
        line2 = line2.strip().split(',')
        mag = float(line2[4])
    print(mag)

我再次尝试获取幅度值并创建一个列表,但我不确定如何仅访问幅度值。谁能指出我正确的方向?

编辑:添加 line1、line2、line2.decode 和 mag 所以我想出了如何获得第一个量级。但是我怎样才能让它们都超过 5 呢?

EDIT2:

好的,所以我想我真正需要帮助的是...如何将数据剥离到它们自己的每一行中?就像我如何编写一个 for 或一个 while 循环来做 line2.strip() 所做的那样?

【问题讨论】:

  • AttributeError: module 'urllib' has no attribute 'request'这是哪个版本的Python?
  • 版本 3.6 运行时没有错误。

标签: python list api url


【解决方案1】:
import requests
import csv

url = 'http://earthquake.usgs.gov/fdsnws/event/1/query'

query = {
    'format': 'csv',
    'starttime': '1916-02-01',
    'latitude': '44.0519',
    'longitude': '-123.0867',
    'maxradiuskm': '250',
    'minmagnitude': '5'
}


response = requests.get(url, params=query)
lines = (line.decode('utf-8') for line in response.iter_lines())
csvreader = csv.DictReader(lines)

现在根据需要迭代数据:

>>> g = iter(csvreader)
>>> next(g)['mag']
'6'
>>> next(g)['mag']
'5.9'
>>> next(g)['mag']
'5.9'
>>> next(g)['mag']
'6'
>>> next(g)['mag']
'5.6'

【讨论】:

    【解决方案2】:

    替代答案,只是为了好玩:尝试使用 Beautiful Soup 来抓取数据。它有一些不错的格式化工具。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多