2014-11-14 2 views
0

내 기능은이 웹 사이트의 데이터를 가져 와서 지진의 위도, 경도, 깊이 및 강도를 수집하도록 설계되었습니다. 두 번째 함수 'colorCode'는 지진의 깊이를 받아서 색상 값을 반환하기로되어 있습니다. 이것은 내가 붙어있는 곳이다. if 문을 사용하여 int와 비교할 수 있도록 데이터를 부동 소수점으로 만들려고했으나 float로 변환 할 수 없다고합니다. 이견있는 사람?지진을 나열하는 기능

import urllib 

#parseEarthquake: int --> list-of-float 

def parseEarthquakeData(numberofearthquakes): 
    URLonWeb = urllib.urlopen("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv") 
    lines = URLonWeb.readlines() 
    numberoflines = len(lines) 
    numberoftimes = 0 
    index = 1 
    myaccumalator = [] 
    for numberoftimes in range(numberofearthquakes): 
     while index < (numberofearthquakes + 1): 
      line = lines[index] 
      data = line.split(",") 
      latitude = float(data[1]) 
      longitude = float(data[2]) 
      depth = float(data[3]) 
      magnitude = float(data[4]) 
      if magnitude < 2.5: 
       magnitude = 2.5 
      myList = [[latitude, longitude, depth, magnitude]] 
      myaccumalator = myaccumalator + myList 
      index = index + 1 
     return(myaccumalator) 


#return [latitude, longitude, depth, magnitude] 

def colorCode(numberofQuakes): 
    data = parseEarthquakeData(2) 
    data =str(data) 
    realdata = data.split() 
    if realdata[2] <34: 
     print 'orange' 
     if realdata[2] >=34<70: 
      print 'yellow' 
      if realdata[2] >=70<150: 
       print 'green' 
       if realdata[2] >=150<300: 
        print 'blue' 
        if realdata[2] >=300<500: 
         print 'purple' 
         if realdata[2] >=500: 
          print 'red' 
+3

나는 모든'if' 문을 그렇게 들여 쓰고 싶지 않습니다. – IanAuld

+2

정확한 오류 메시지는 무엇입니까? – tripleee

답변

0

파이썬은 당신이 달성하려고하는 것에 대해 매우 편리한 csv.DictReader 모듈이 (내가 잘못된 형식으로 코드를 게시 할 경우 실례).

dictReader
import urllib 
import csv 

#parseEarthquake: int --> list-of-float 

def parseEarthquakeData(numberofearthquakes): 
    URLonWeb = urllib.urlopen("http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_month.csv") 
    lines = URLonWeb.readlines() 
    content = csv.DictReader(lines) 
    allEarthquakes = [line for line in content] 
    return allEarthquakes[:numberofearthquakes] 


#return [latitude, longitude, depth, magnitude] 

def colorCode(numberofQuakes): 
    data = parseEarthquakeData(2) 
    for earthquake in data: 
     depth = float(earthquake["depth"]) 
     print(depth) 
     if depth <34: 
      print 'orange' 
     elif 34 <= depth <70: 
      print 'yellow' 
     if 70 <= depth <150: 
      print 'green' 

CSV 파일에서 해당 헤더를 사전에 모든 라인을 변환 : 나는 그것이 더 짧고 readbale하기 위해 약간의 주위에 당신의 코드를 변경했습니다. 이렇게하면 구조화 된 데이터가 목록과 비교하여 사전에서 훨씬 더 읽기 쉽기 때문에 (어떤 위치가 무엇인지 기억할 필요가 없기 때문에) 좋습니다.

당신은 또한 색상 코드 방법의 숫자 비교에 몇 가지 문제가 있었는데, 당신이 그것을 내가 무엇을 변경 비교. 또한 당신이 달성하기를 원하는 것을 말할 수 없습니다 data =str(data)

저는 전체 컬러 로직을 구현하지 않았지만 사용자의 요구에 맞게 조정할 수 있어야합니다.

관련 문제