Amazing-Python-Scripts

Форк
0
54 строки · 1.5 Кб
1
import io
2
import os
3
import sys
4
from contextlib import contextmanager
5

6
import newsapi
7
from gtts import gTTS
8
from pydub import AudioSegment
9
from pydub.playback import play
10

11
more_news = True
12
article_number = 0
13

14

15
def fetch_news() -> dict:
16
    query = input("What do you want to hear about? ")
17
    return newsapi.get_everything(q=query)
18

19

20
# To play audio text-to-speech during execution
21
def speak(text: str):
22
    with io.BytesIO() as f:
23
        gTTS(text=text, lang='en').write_to_fp(f)
24
        f.seek(0)
25
        audio = AudioSegment.from_file(f, format="mp3")
26
        play(audio)
27

28

29
if __name__ == '__main__':
30
    with open("api_key.txt", "r") as file:
31
        api_key = file.readline()
32
    newsapi = newsapi.NewsApiClient(api_key=api_key)
33

34
    headlines = fetch_news()
35
    while more_news:
36
        article_number += 1
37
        try:
38
            print()
39
            article = headlines["articles"][article_number]
40
            print(article["title"], "-", article["source"]["name"])
41
            speak(article["title"])
42
            print(article["description"])
43
            speak(article["description"])
44
            print("Continue reading on this URL:", article["source"]["name"])
45
        except IndexError:
46
            speak(
47
                "It looks as there are no more news on this topic. Why not search something else? "
48
            )
49
        except KeyboardInterrupt:
50
            break
51
        if article_number == 10:
52
            article_number = 0
53
            if input("Want to hear more news? [y/n] ") != "y":
54
                more_news = False
55

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.