Write python to take a file that is divided into sections (separated by 2 or more…
- User
Write python to take a file that is divided into sections (separated by 2 or more newlines) that have the following headers: [verse][chorus][bridge][outro]. Create song lyrics based on random choice of these sections, but maintaining the following structure: [verse][chorus][verse][bridge][verse][outro]
Assistant
Okay, here's a Python script that accomplishes this.
It reads the input file, splits it into sections based on two or more newlines, categorizes the sections based on the headers (
[verse],[chorus],[bridge],[outro]), stores them, and then generates a new song by randomly selecting sections according to the specified structure.import re import random import os import sys def load_and_categorize_sections(filename): """ Reads a file, splits it into sections by two or more newlines, and categorizes the content based on headers like [verse], [chorus], etc. Args: filename (str): The path to the input file. Returns: dict: A dictionary where keys are section types (str) and values are lists of section content (str). Returns None if the file cannot be read or no valid sections are found. """ sections = { 'verse': [], 'chorus': [], 'bridge': [], 'outro': [] } valid_headers = { '[verse]': 'verse', '[chorus]': 'chorus', '[bridge]': 'bridge', '[outro]': 'outro' } try: with open(filename, 'r', encoding='utf-8') as f: content = f.read() except FileNotFoundError: print(f"Error: File not found at {filename}") return None except Exception as e: print(f"Error reading file {filename}: {e}") return None # Split content by two or more newlines raw_sections = re.split(r'\n{2,}', content) for raw_section in raw_sections: stripped_section = raw_section.strip() if not stripped_section: continue # Skip empty sections resulting from splitting # Find the header at the beginning of the section found_header = None section_type = None section_content = stripped_section for header_tag, s_type in valid_headers.items(): if stripped_section.startswith(header_tag): found_header = header_tag section_type = s_type # Remove the header and any leading/trailing whitespace around content section_content = stripped_section[len(header_tag):].strip() break # Found the header, stop checking if found_header and section_content: sections[section_type].append(section_content) elif found_header and not section_content: print(f"Warning: Found header '{found_header}' but no content following it. Skipping.") elif stripped_section: print(f"Warning: Section found without a recognized header. Skipping section starting with:\n'{stripped_section[:50]}...'") # Check if we have at least one of each required type for the structure required_types = ['verse', 'chorus', 'bridge', 'outro'] for req_type in required_types: if not sections[req_type]: print(f"Error: No sections found for type '{req_type}'. Cannot generate song with the required structure.") return None return sections def generate_song_structure(sections_dict): """ Generates a song by randomly selecting sections based on a predefined structure. Args: sections_dict (dict): A dictionary containing categorized song sections. Returns: str: The generated song lyrics, or None if a required section type is missing in the input data. """ if sections_dict is None: return None # Indicate failure from loading # Define the desired song structure # [verse][chorus][verse][bridge][verse][outro] structure = ['verse', 'chorus', 'verse', 'bridge', 'verse', 'outro'] generated_parts = [] for section_type in structure: available_sections = sections_dict.get(section_type) if not available_sections: # This check should ideally be caught by the loading function, # but is included here as a safeguard. print(f"Error: Cannot find any '{section_type}' sections to fulfill the structure.") return None # Randomly choose one section of the required type chosen_section = random.choice(available_sections) generated_parts.append(chosen_section) # Join the parts with two newlines as separation return '\n\n'.join(generated_parts) if __name__ == "__main__": # Get the input filename from command line arguments or prompt if len(sys.argv) > 1: input_filename = sys.argv[1] else: input_filename = input("Enter the path to the input song sections file: ") # Load and categorize the sections song_sections = load_and_categorize_sections(input_filename) if song_sections: # Generate the song based on the structure generated_lyrics = generate_song_structure(song_sections) if generated_lyrics: print("\n--- Generated Song Lyrics ---") print(generated_lyrics) print("-----------------------------") # Optional: Save the generated lyrics to a file output_filename = "generated_song.txt" try: with open(output_filename, "w", encoding="utf-8") as outfile: outfile.write(generated_lyrics) print(f"\nGenerated lyrics saved to {output_filename}") except Exception as e: print(f"Error saving generated lyrics to file: {e}")How to Use:
-
Save the code: Save the code above as a Python file (e.g.,
song_generator.py). -
Create an input file: Create a text file (e.g.,
my_lyrics.txt) with your song sections. Make sure:- Each section starts with one of the headers:
[verse],[chorus],[bridge], or[outro]. - The text of the section follows immediately after the header (optionally with some whitespace).
- Sections are separated by two or more blank lines.
- You can have multiple instances of
[verse]and[chorus](which is necessary for random choice). You only need at least one[bridge]and one[outro]to satisfy the structure.
Example
my_lyrics.txt:[verse] Walking down the street today Sunlight shining on my way Thinking thoughts I cannot say Hope tomorrow's a better day This is verse 1 content. [chorus] Oh, the rhythm of the city beat Moving fast on concrete feet Life's a bittersweet, lovely treat Can you feel the summer heat? This is the main chorus. [verse] See a face I know so well Stories that I cannot tell Underneath the city's spell In this concrete living hell (just kidding!) This is verse 2 content. [bridge] A moment of quiet introspection Seeking peace and redirection Breaking from the main connection Finding inner calm and affection This part offers a change. [chorus] Oh, the rhythm of the city beat Moving fast on concrete feet Life's a bittersweet, lovely treat Can you feel the summer heat? This is the main chorus again. [outro] Fade away now, fade away Another ending to the day Let the music gently play Until the morning light of May The song concludes here. - Each section starts with one of the headers:
-
Run the script:
- Open your terminal or command prompt.
- Navigate to the directory where you saved the files.
- Run the script, providing the input filename as an argument:
python song_generator.py my_lyrics.txt - Alternatively, run without an argument and it will prompt you for the filename:
python song_generator.py
The script will print the generated song lyrics to the console and also save them to a file named
generated_song.txt. Each run might produce a different combination of verses if you have multiple verse options in your input file.-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.