Python final project is "pythonic"?


Hi all,
I just finished my Python project: it is supposed to take songtext of a same band (Paramore), produce a new song text and read it out loud.
I used the codecademy library for Markov Chains.
The code seems to work fine, but I would like to know if there are ways to make it more “pythonic” avoiding commands that usually people don’t like.
I’m a beginner, so I don’t know much about what I’m supposed to use and what not!

Below you can find my functions, but the entire project can be found here:

Any suggestions are very welcome!
Thank you!

from bs4 import BeautifulSoup

#url_file is a file with only one column consisting of urls
#name_of_lyrics is the name of the txt file to which we write the "decomposed" lyrics

def lyrics(url_file, name_of_lyrics):
        with open(url_file, 'r') as f:
            links = [line.translate({ord(c): "" for c in '\n'}) for line in f.readlines()] 
        page = []
        for i in range(len(links)):
            if requests.get(links[i]).status_code == 200:  
        print('The first entry is not a valid file name')

        with open(name_of_lyrics, 'w') as f:
            for i in range(len(page)):
                soup = BeautifulSoup(page[i].text, 'html.parser')
                song = soup.find_all(id="lyrics")[0].get_text() 
                song = song.translate({ord(c): " " for c in '()""?!.,\n'}) 
        print('The second entry is not a valid file name')

#Create a new song with lyrics takes from a txt file previously created

#needed libraries: codecademy module for Markov Chains

from markov_python.cc_markov import MarkovChain

#lyrics_file is the name of the file with the lyrics, n is the number of time we run the generate_text function

def new_song(lyrics_file, n):

    mc = MarkovChain() 
    new = [] 

    if n > 0:
        for i in range(int(n)):
            new += mc.generate_text() #output a list of words
        new = ["I" if x=="i" else "I'm" if x=="i'm" else x for x in new] 
        song = '\n'.join([' '.join(new[5 * i: 5 * i + 5]) for i in range(int(len(new) / 5))]) 
        print('The chosen number is not valid')
        song = ''
    return song

#Converting the text to speech

#needed libraries

import pyttsx

#songtext is a string

def read_out_loud(songtext):
    if isinstance(songtext, str):
        engine = pyttsx.init()
        engine.setProperty('rate', 30)
        engine = pyttsx.init()
        engine.setProperty('rate', 30)
        engine.say('I can\'t read your input')


Hi @latozzo,

Your code looks good. It makes nice use of list comprehensions.

You could try to combine these lines into one that uses a list comprehension, but it’s not critical that you do so …

        page = []
        for i in range(len(links)):
            if requests.get(links[i]).status_code == 200:  

Nice project :smile:.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.