I’m writing code that receives as input song lyrics as a .txt file with periods separating the different parts and am having trouble creating a for loop in python that does the separation properly. For some reason it the index always goes back to the first separating line.
here is the function:
with open(os.path.join(file_path, file_name), 'rt', encoding='utf-8') as file:
songlyrics = file.read()
songlyrics = str(songlyrics)
split_lyrics = songlyrics.splitlines()
print(split_lyrics)
print("SEPARATE START n")
count = -1
lyrics_in_page = []
for line in split_lyrics:
count += 1
print("Count: ", count, "Line: ", split_lyrics.index(line))
if '.' in line:
print("SEPARATE n")
line_index = split_lyrics.index(line)
print("Line index: ", line_index)
start = line_index - count
end = line_index
songpart = split_lyrics[start:end]
print("songpart at: ", start, end)
print(songpart)
count = -1
and here is what it outputs:
['Noche de paz, noche de amor', 'Todo duerme alrededor', 'Entre los astros que esparcen su luz', 'Bella, anunciando al niño Jesús', 'Brilla la estrella de paz', 'Brilla la estrella de amor', '.', 'Noche de paz, noche de luz', 'Ha nacido Jesús', 'Pastorcillos que oíd anunciar', 'No temáis cuando entréis a adorar', 'Que ha nacido el amor', 'Que ha nacido el amor', '.', 'Desde el pesebre del niño Jesús', 'La Tierra entera se llena de luz', 'Porque ha nacido Jesús', 'Entre canciones de amor', '.']
SEPARATE START
Count: 0 Line: 0
Count: 1 Line: 1
Count: 2 Line: 2
Count: 3 Line: 3
Count: 4 Line: 4
Count: 5 Line: 5
Count: 6 Line: 6
SEPARATE
Line index: 6
songpart at: 0 6
['Noche de paz, noche de amor', 'Todo duerme alrededor', 'Entre los astros que esparcen su luz', 'Bella, anunciando al niño Jesús', 'Brilla la estrella de paz', 'Brilla la estrella de amor']
Count: 0 Line: 7
Count: 1 Line: 8
Count: 2 Line: 9
Count: 3 Line: 10
Count: 4 Line: 11
Count: 5 Line: 11
Count: 6 Line: 6
SEPARATE
Line index: 6
songpart at: 0 6
['Noche de paz, noche de amor', 'Todo duerme alrededor', 'Entre los astros que esparcen su luz', 'Bella, anunciando al niño Jesús', 'Brilla la estrella de paz', 'Brilla la estrella de amor']
Count: 0 Line: 14
Count: 1 Line: 15
Count: 2 Line: 16
Count: 3 Line: 17
Count: 4 Line: 6
SEPARATE
Line index: 6
songpart at: 2 6
['Entre los astros que esparcen su luz', 'Bella, anunciando al niño Jesús', 'Brilla la estrella de paz', 'Brilla la estrella de amor']
Process finished with exit code 0
Any help would be greatly appreciated! I know this seems like a silly beginner mistake and is probably a simple thing I overlooked.
I’ve tried changing the indexes and the counts, but shouldn’t the if statement reset the variables I’m declaring? (line_index
doesn’t seem to change ever which is confusing). The print statements were added to see what was really happening.
Enica is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.