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
Мой вопрос, почему я получая эту ошибку и как ее исправить?
Можете ли вы опубликовать код, используемый для вызова функции? – electrometro
avg_temp_march ("http://robjhyndman.com/tsdldata/data/cryer2.dat") или плохо, просто сделайте avg_temp_march (url), так как у меня есть URL-адрес имен переменных, который уже является самим URL-адресом – AFC
Вам не хватает шага, вы загружаете данные по URL-адресу. Для этого вы можете использовать что-то вроде [urllib2] (https://docs.python.org/2/library/urllib2.html#examples). –