TextToHTML with File Integration - Python Programming Exercise

In this exercise, you will develop a Python program to enhance the TextToHTML class by adding the ability to save its results into a text file. This exercise is perfect for practicing class definition, method implementation, and file handling in Python. By implementing this class, you will gain hands-on experience in handling class definitions, method implementation, and file handling in Python. This exercise not only reinforces your understanding of object-oriented programming but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

Texttohtml With File Integration

 Objective

Develop a Python program to enhance the TextToHTML class by adding the ability to save its results into a text file. Include a method named save_to_file, which will take the file name as an argument and write the generated HTML content to it.

Tip: Use a file writing mechanism like open() with the mode set to "w" to handle the file operations.

 Example Python Exercise

 Copy Python Code
class TextToHTML:
    """
    A class to convert multiple sentences into HTML format.
    Includes methods to add sentences, display them, and convert them into HTML.
    """
    
    def __init__(self):
        # Initialize an array to store the sentences
        self.sentences = []
    
    def add(self, text):
        """
        Adds a new string to the list of sentences.
        """
        self.sentences.append(text)
    
    def display(self):
        """
        Displays all sentences in HTML format.
        """
        for sentence in self.sentences:
            print(f"

{sentence}

") def to_string(self): """ Returns all sentences as a single string in HTML format, separated by new lines. """ html_content = "" for sentence in self.sentences: html_content += f"

{sentence}

\n" return html_content def save_to_file(self, file_name): """ Saves the generated HTML content to a text file. Writes the sentences as HTML paragraphs. """ try: with open(file_name, 'w') as file: html_content = self.to_string() # Get the HTML formatted content file.write(html_content) # Write it to the file print(f"HTML content successfully saved to {file_name}.") except Exception as e: print(f"Error saving to file: {e}") # Auxiliary class with a main function to test the TextToHTML class class Main: def __init__(self): self.text_to_html = TextToHTML() def run(self): """ Runs the main program: collects text, displays HTML, and saves to a file. """ print("Enter sentences (press Enter without typing anything to finish):") while True: sentence = input() if not sentence: # Stop when the input is empty break self.text_to_html.add(sentence) # Add sentence to the TextToHTML object print("\nHTML representation of the sentences:") self.text_to_html.display() # Display the HTML representation of the sentences # Ask for the file name to save the content file_name = input("\nEnter the file name to save the HTML content: ") self.text_to_html.save_to_file(file_name) # Save the HTML to a file # Run the program if __name__ == "__main__": main_program = Main() main_program.run()

 Output

Enter sentences (press Enter without typing anything to finish):
Hello
How are you?
This is a test.

HTML representation of the sentences:

Hello

How are you?

This is a test.

Enter the file name to save the HTML content: output.html HTML content successfully saved to output.html.

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  Log Handler

    In this exercise, you will develop a Python program with a class called Logger, which includes a static method called log. This exercise is perfect for practic...

  •  More

    In this exercise, you will develop a Python program that mimics the behavior of the Unix "more" command. This exercise is perfect for practicing file handling,...

  •  Text Modifier

    In this exercise, you will develop a Python program that reads a text file, replaces specified words, and saves the modified content into a new file. This exercise...

  •  Count characters in a text file

    In this exercise, you will develop a Python program that counts how many times a specific character appears in a given file (of any type). This exercise is per...

  •  Binary File Reading (BMP Example)

    In this exercise, you will develop a Python program that verifies if a BMP image file is valid by checking its header. This exercise is perfect for practicing ...

  •  Saving Data to a Binary File

    In this exercise, you will develop a Python program that prompts the user to enter their name, age (as a byte), and birth year (as an integer), then saves this inform...