Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend March 27, 2020, 8:13 p.m. ⋅ 2711 views

Building a news headlines player using Python and text to speech


In this article, I'll build a bot that will fetch latest news from internet and read it out.

I'll be using pyttsx3 for text to speech and requests, BeautifulSoup for web scrapping to fetch news.

So, let's install both of them first.

pip install bs4

 

pip install -U pyttsx3==2.71

 

Now let's fetch the news headlines from Times Of India.

import requests
from bs4 import BeautifulSoup

# Getting news from Times of India

toi_r = requests.get("https://timesofindia.indiatimes.com/briefs")
toi_soup = BeautifulSoup(toi_r.content, 'html5lib')

toi_headings = toi_soup.find_all('h2')

toi_headings = toi_headings[0:-13] # removing footers

toi_news = []

for th in toi_headings:
    toi_news.append(th.text)

 If you are wondering about how i came up with above script, do read my article on Building news aggregator web app

In that article I have dicusssed in details about how to do web scrapping for news. Now, let's move on to building player part.

Here is how you make computer speak anything.

import pyttsx3 

# get an engine instance
engine = pyttsx3.init() 

# Pass what we want it to say
engine.say('Hello buddy. Welcome to HackersFriend')

# run and wait method, it processes it
engine.runAndWait() 

Again, I have dicussed about implementing text-to-speech in seperate article. You can check it out from here. Python - Text to Speech by using pyttsx3

 

Now, let's integrate both parts to build our final product, The news player.

import requests
from bs4 import BeautifulSoup
import pyttsx3

# Getting news from Times of India

toi_r = requests.get("https://timesofindia.indiatimes.com/briefs")
toi_soup = BeautifulSoup(toi_r.content, 'html5lib')

toi_headings = toi_soup.find_all('h2')

toi_headings = toi_headings[0:-13] # removing footers

toi_news = []

for th in toi_headings:
    toi_news.append(th.text)

# got all the news.

# Play the news

engine = pyttsx3.init() # get the player engine

for news in toi_news:
    engine.say(news)


# run and wait method, it processes it
engine.runAndWait() 

 

You can find the entire code from here.

https://github.com/irajankumar/News-HeadLines-Player/ 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account