In [ ]:
# Import datetime to use dates.
from datetime import *
In [ ]:
# The data comes in a dictionary (key-value pairs). Note that it looks just like JSON!
data = {
"Richter": 7.5,
"Latitud": 12,
"Longitud": 12,
"City": "Gothenburg",
"Country": "Sweden",
"Datetime": "2017-02-01 22:15:43"
}
In [ ]:
# We start with the assumption that the data is news worthy.
IsNewsWorthy = True
# Are there errors in the data?
if data["Richter"] > 100:
# A earthquake with magnitue of 100 seems unlikely, so we ignore it.
IsNewsWorthy = False
# We are only interested in earthquakes in Sweden.
if data["Country"] != "Sweden":
IsNewsWorthy = False
Basically, it's just a lot of if-statements.
How to make the code easier to read:
if-statements inside each other too much. Use elif instead.""" around them..format on strings.text = "My name is {0} and I am {1} years old"
text = text.format(Name, Age)
Which is the same as this:
text = "My name is " + Name + " and I am " + str(Age) + " years old"
In [ ]:
# If the earthquake is deemed news worthy, then create a journalistic text.
text = ""
if IsNewsWorthy:
if (data["Richter"] > 6):
# Text for large quake (6+).
text = """BREAKING: Major earthquake in {0}
Today at {1} there was a severe earthquake in {2}, {3}, with a magnitude of {4} on the Richter scale.
"""
text = text.format(data["City"], data["Datetime"], data["City"], data["Country"], data["Richter"])
elif (data["Richter"] < 6 or data["Richter"] >= 3):
# Text for medium quake (3-5).
text = """Earthquake in {0}
Today at {1} there was a earthquake in {2}, {3}, with a magnitude of {4} on the Richter scale.
"""
text = text.format(data["City"], data["Datetime"], data["City"], data["Country"], data["Richter"])
# Add this at the end of all texts.
text = text + "Published " + datetime.now().strftime("%Y-%m-%d %H:%M") + " by Ada the news robot"
In [ ]:
# Look at the text
print(text)
In [ ]:
# Function to save the text to a file.
def savefile(filename, text):
f = open(filename, mode="w") # Open file for writing (w = writing, a = append, r = reading)
f.write(text)
f.close()
In [ ]:
# Only save as text file if there is some text.
if text != "":
savefile("newsrobot-earthquake.txt", text)
print("Text published!")
else:
print("Text is not published.")
In [ ]:
# Function that reads text from a file.
def readfile(filename):
f = open(filename, mode="r") # Open file for reading (w = writing, a = append, r = reading)
lines = f.read()
f.close()
return(lines)
In [ ]:
# Read the file created earlier by the news robot.
text = readfile("newsrobot-earthquake.txt")
In [ ]:
# Look at the text from the file.
print(text)