2015-03-03 2 views
0
def avg_temp_march(f): 
'''(file) -> float 
Return the average temperature for the month of March 
over all years in f. 
''' 

# We are providing the code for this function 
# to illustrate one important difference between reading from a URL 
# and reading from a regular file. When reading from a URL, 
# we must first convert the line to a string. 
# the str(line, 'ascii') conversion is not used on regular files. 

march_temps = [] 

# read each line of the file and store the values 
# as floats in a list 
for line in f: 
    line = str(line, 'ascii') # now line is a string 
    temps = line.split() 
    # there are some blank lines at the end of the temperature data 
    # If we try to access temps[2] on a blank line, 
    # we would get an error because the list would have no elements. 
    # So, check that it is not empty. 
    if temps != []: 
     march_temps.append(float(temps[2])) 

# calculate the average and return it 
return sum(march_temps)/len(march_temps) 

Итак, у меня есть эта функция, предоставленная мне. Вы должны ввести URL-адрес в него (один я использую http://robjhyndman.com/tsdldata/data/cryer2.dat), и он будет читать и преобразовать в строку, но проблема в том, что это дает мне эту ошибкуЧтение с веб-сайта

Traceback (most recent call last): 
    File "<pyshell#38>", line 1, in <module> 
    avg_temp_march(file) 
    File "C:\Users\USER\Desktop\work\files.py", line 42, in avg_temp_march 
    line = str(line, 'ascii') # now line is a string 
TypeError: decoding str is not supported 

Мой вопрос, почему я получая эту ошибку и как ее исправить?

+0

Можете ли вы опубликовать код, используемый для вызова функции? – electrometro

+0

avg_temp_march ("http://robjhyndman.com/tsdldata/data/cryer2.dat") или плохо, просто сделайте avg_temp_march (url), так как у меня есть URL-адрес имен переменных, который уже является самим URL-адресом – AFC

+0

Вам не хватает шага, вы загружаете данные по URL-адресу. Для этого вы можете использовать что-то вроде [urllib2] (https://docs.python.org/2/library/urllib2.html#examples). –

ответ

0

Я не совсем уверен, что вы после, но это, похоже, делает трюк. Главное, о чем я не был уверен, было то, что вводит avg_temp_march. Это файл, список строк, URL-адрес или что-то еще?

Имеет значение, поскольку вам нужно знать, сколько обработки выполняется до его вызова.

from urllib.request import urlopen 

def avg_temp_march(f): 
    march_temps = [] 

    # line does a lot it 
    # strips away new line and whitespace 
    # decodes to utf-8 
    # splits the values by space 
    # does not include lines which are empty 
    temps = [line.strip().decode(encoding='utf-8').split() for line in f if line != b'\n'] 

    # skip first 3 lines as they are not part of the actual data 
    for t in temps[3:]: 
     # take average temperatures for only march 
     # the 3rd month at index 2 
     march_temps.append(float(t[2])) 

    return sum(march_temps)/len(march_temps) 


f = urlopen("http://robjhyndman.com/tsdldata/data/cryer2.dat") 
print (avg_temp_march(f)) 

Позвольте мне знать, что правильно или неправильно об этом, и я могу изменить или удалить по мере необходимости.