Skip to content
Snippets Groups Projects
Commit 20b6d543 authored by Joonas Seppä's avatar Joonas Seppä
Browse files

Better news program

parent 4889c269
No related branches found
No related tags found
No related merge requests found
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "pwa-chrome",
"request": "launch",
"name": "Open jsProject.html",
"file": "/Users/joonasseppa/Desktop/Koulu/training/jsProject.html"
}
]
}
\ No newline at end of file
No preview for this file type
from myNewsClass import NewsByCountry
print()
number=5
while(True):
print("If you need instructions, type 'info'")
print("What country do you want news from?: ")
NewsByCountry.callNews(input())
\ No newline at end of file
userInput = input()
if userInput=="exit":
break
number = NewsByCountry.callNews(userInput, number)
#If number -1 is returned, an error has happened
if number == -1:
break
\ No newline at end of file
from asyncio.windows_events import NULL
import requests
import json
import textwrap
from urllib.request import urlopen
#import xml.parsers.expat
from xml.dom.minidom import parse, parseString
import xml.etree.ElementTree as ET
import xmltodict
class NewsByCountry:
def callNews(countryString):
def callNews(countryString, number):
if(countryString=="iltalehti"):
iltalehtiURL = requests.get("https://www.iltalehti.fi/rss/uutiset.xml")
iltalehtiDICT = xmltodict.parse(iltalehtiURL.content)
#MUUTIN TÄSSÄ DICT-FORMAATIN JSON:iksi. Nähtävästi DICT toimii jo samalla tavalla.
#PIDETÄÄN KUITENKIN KOODI TÄSSÄ JOS JSON:ia TARVITSEE!
#iltalehtiJSON = json.dumps(iltalehtiDICT)
#iltalehtiJSONOikea = json.loads(iltalehtiJSON)
#json.loads MUUTTAA JSON:IN DICTIONARYKSI; siis iltalehtiJSONOikea~iltalehtiDICT
#Tyyppi ei ole täysin sama; toinen on ordered dictionary ja toinen perus dictionary
#Mutta joka tapauksessa, pythonissa kannattaa käyttää dictionarya koska JSON:sta ei voi ottaa
#osia helposti
#iltalehti = iltalehtiJSONOikea["rss"]["channel"]["item"]
iltalehti = iltalehtiDICT["rss"]["channel"]["item"]
for i in range(10):
print()
howManyToShow = 0
if number > len(iltalehti):
howManyToShow = len(iltalehti)
elif number <= len(iltalehti):
howManyToShow = number
for i in range(howManyToShow):
#print(iltalehti[i]["title"])
publishableArticle = textwrap.wrap(iltalehti[i]["description"], 80)
for i in publishableArticle:
print(i)
print()
return number
if(countryString=="info"):
for i in range(10):
print()
print()
print("Hello! Welcome to my news-program!")
print("This program uses 'newsapi.org' to get news from different sources")
......@@ -15,13 +62,36 @@ class NewsByCountry:
print("To get news from a country, input country's short form, eg. 'us'")
print("Country names must be written in lower-case")
print()
print("To change the amount of news, input an integer, eg. '10'")
print()
print("If you wan't to leave the program, input 'exit'")
print()
print("In Finnish you can get news from Iltalehti with input 'iltalehti'")
print()
print("All possible country inputs are: ")
print("at, au, be, bg, br, ca, ch, cn, co, cu, cz, de, eg, fr, gb, gr, hk, hu, id, ie, il, in, it, jp, kr, lt, lv, ma, mx, my, ng, nl, no, nz, ph, pl, pt, ro, rs, ru, sa, se, sg, si, sk, th, tr, tw, ua, us, ve, za")
print("Please note that news can can be in other languages than English!")
print()
#Update this list when you can
print("You can find news in English from: au = Australia, ca = Canada, gb = Great Britain, us = USA")
print("And possibly from: hk=Hong Kong, ie = Ireland, in=India, jp=Japan, mx=Mexico, nz=New zealand, sg=singapore, za=south africa")
print()
else:
if countryString.isnumeric():
newNumber = int(countryString)
number = newNumber
for i in range(10):
print()
print("Number of news changed to " + str(number))
print()
print("Top 5 news from '" + countryString + "':")
return number
for i in range(10):
print()
print()
print("Top " + str(number) + " news from '" + countryString + "':")
url = "https://newsapi.org/v2/top-headlines?country=" + countryString + "&apiKey=9a5f1610264d4831b94ba00b1bdbd885"
......@@ -29,28 +99,65 @@ class NewsByCountry:
someCountry = requests.get(url)
content = json.loads(someCountry.content)
if(content["totalResults"]<5):
if(content["status"]=="ok"):
pass
elif(content["status"]=="error"):
print()
print("LESS THAN 5 RESULTS")
print("This many results: ")
print(content["totalResults"])
print("Unknown error happened!")
print()
print("This probably means that country's name is wrong or country not supported")
print("This is what we got from the server: ")
print(content)
print()
number = -1
return number
else:
if(content["code"]=="rateLimited"):
print()
print("Error!")
print("You have made too many requests")
print("Free accounts are limited to 50 requests in 12 hours")
print()
print("Here is the complete error message from server in JSON format: ")
print(content)
print()
number = -1
return number
articles = content["articles"]
if(content["totalResults"]<1):
print()
print("ERROR: 0 RESULTS")
#print(str(content["totalResults"]) + " results")
#print(content["totalResults"])
print()
print("This probably means that country's name is wrong or country is not supported")
print()
else:
articles = content["articles"]
results = len(articles)
print()
printableNumber = 0
if(number>=len(articles)):
printableNumber = len(articles)
else:
printableNumber = number
for i in range(5):
for i in range(printableNumber):
print(((articles[i])["source"])["name"] + ":")
if(articles[i]["description"]==NULL or articles[i]["description"]=="" or articles[i]["description"]==" "):
if(articles[i]["description"]==None or articles[i]["description"]=="" or articles[i]["description"]==" "):
#Description is null, trying content:
if(articles[i]["content"]==NULL or articles[i]["content"]=="" or articles[i]["content"]==" "):
print("The content is also null, no can do")
if(articles[i]["content"]==None or articles[i]["content"]=="" or articles[i]["content"]==" "):
print("(This article has no description and no content!)")
print()
else:
article = articles[i]["content"]
......@@ -67,3 +174,8 @@ class NewsByCountry:
for i in publishableArticle:
print(i)
print()
if(results<number):
print("Found only " + str(results) + " results!")
print()
return number
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment