I need some help with a task in python.
The task is to make a program that downloads a text file from the internet.
Then you have to find "Saturday" and "Sunday" in the text file.
Next to those are the temperatures.
The task is to calculate the average temperature of the weekend.
I am not allowed to change the text file.
Here is an example of the text file contents:
Thursday: 21
Friday: 19
Saturday: 13
Sunday: 17
Monday: 19
Tuesday: 21
Wednesday: 16
well… i found which line they are but i don’t know how to get the temperatures. I need to seperate the numbers from the text and assign them to my two variables temp1 and temp2.
I would be grateful if you could help me.
(sorry for my english. i am not a native speaker.)
import urllib.request
my_list = list()
word1 = "Saturday"
word2 = "Sunday"
temp1 = 0
temp2 = 0
average = (temp1 + temp2) / 2
urllib.request.urlretrieve("https://www.senarclens.eu/~gerald/teaching/cms/data/fc.txt", "fc.txt")
open('fc.txt', 'r')
with open('fc.txt') as f:
lines = f.read().split("\n")
for i, line in enumerate(lines):
if word1 in line:
print("Word \"{}\" found in line {}".format(word1, i + 1))
for i, line in enumerate(lines):
if word2 in line:
print("Word \"{}\" found in line {}".format(word2, i + 1))
# need the temperature next to the name of day for temp1, temp2
if average > 25:
print("Next weekend, swimming would be a good activity.")
elif average >= 12 and average < 25:
print("Next weekend, hiking would be a good activity.")
elif average >= 5 and average < 12:
print("Next weekend, watching movies would be a good activity.")
elif average >= -5 and average < 5:
print("Next weekend, relaxing in the local hot springs would be a good activity.")
else:
print("Next weekend, skiing would be a good activity.")
>Solution :
If the text file is always going to be in this format, you can use a split function and not worry about regex ever.
You won’t need two for loops
daily_temps = {}
for i, line in enumerate(lines):
splits = line.split(":")
day = splits[0].strip()
temp = int(splits[-1].strip())
daily_temps[day] = temp
The strip removes any extra spaces
This will give you
{'Thursday': 25, 'Friday': 19, 'Saturday': 13 ...}
Then you do
temp1 = daily_temps['Saturday']
temp2 = daily_temps['Sunday']
average = (temp1 + temp2) / 2
if average > 25:
print("Next weekend, swimming would be a good activity.")
The average declaration you have before you set temp1 and temp2 is wrong. Declare it after they’ve been set.