0
votes

I am using python to read numeric weather data from a file and then checking the humidity conditions. If the humidity is less than or equal to 75 then the humidity should be re-written as "low" and if the humidity is greater than 75 then it should be re-written as "high". Following is my data in the file.

outlook, temperature, humidity, windy, permission_to_play

  1. sunny,85,85,FALSE,no
  2. sunny,80,90,TRUE,no
  3. overcast,83,86,FALSE,yes
  4. rainy,70,96,FALSE,yes
  5. rainy,68,80,FALSE,yes
  6. rainy,65,70,TRUE,no
  7. overcast,64,65,TRUE,yes
  8. sunny,72,95,FALSE,no
  9. sunny,69,70,FALSE,yes
  10. rainy,75,80,FALSE,yes
  11. sunny,75,70,TRUE,yes
  12. overcast,72,90,TRUE,yes
  13. overcast,81,75,FALSE,yes
  14. rainy,71,91,TRUE,no

I am reading this file in a list and then accessing the humidity value. Following is the code I have written.

def fetchData(fileName):
    datalist = []
    rd =open(fileName,mode='r')
    list = rd.readlines()
    for l in list:
        subList = l.strip().split(',')
        humidity=subList[2]
        if humidity>75:
            subList[2]="high"
        else:
            subList[2]="low"
        datalist.append(subList)
    return datalist

dataList = fetchData('weather.numeric.data')
print dataList

After execution of this, data numbers 6,7,9,11,13 should have their humidity value as low and the others should be high. But all the humidity values are becoming high, as seen in the output below.

[['sunny', '85', 'high', 'FALSE', 'no'], ['sunny', '80', 'high', 'TRUE', 'no'], ['overcast', '83', 'high', 'FALSE', 'yes'], ['rainy', '70', 'high', 'FALSE', 'yes'], ['rainy', '68', 'high', 'FALSE', 'yes'], ['rainy', '65', 'high', 'TRUE', 'no'], ['overcast', '64', 'high', 'TRUE', 'yes'], ['sunny', '72', 'high', 'FALSE', 'no'], ['sunny', '69', 'high', 'FALSE', 'yes'], ['rainy', '75', 'high', 'FALSE', 'yes'], ['sunny', '75', 'high', 'TRUE', 'yes'], ['overcast', '72', 'high', 'TRUE', 'yes'], ['overcast', '81', 'high', 'FALSE', 'yes'], ['rainy', '71', 'high', 'TRUE', 'no']]

what changes should I make? Thanks in advance! :)

2
You are reading strings and comparing them to ints! Cast to int before comparing to 75: humidity=int(subList[2]) - user2390182

2 Answers

2
votes

You should convert string to int before comparing with 75:

if int(humidity)>75:
0
votes

1 Open file with 'with' statment:

 with open (filename, "r") as rd:
    #don't use list - it is a type name
    mylist = rd.readlines()
 for l in mylist .....

2 cast the values to int:

try humidity = int(humidity):
    if humidity>75:
        subList[2]="high"
    else:
        subList[2]="low"
except:
    return 'bad values in file - humidity is not a number'