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
Show 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