Exercise: Classes

Exercise 1: Create a Simple Text Class

Task: Write a class that represents a simple text document.

Instructions:

  • Define a class called TextDocument with the following attributes:
    • title (string)
    • content (string)
  • Include a method called word_count() that returns the number of words in the content.
  • Create an instance of the TextDocument class, set the title and content, and print the word count.
Show solution
class TextDocument:
    def __init__(self, title, content):
        self.title = title
        self.content = content
    
    def word_count(self):
        return len(self.content.split())

# Sample usage
doc = TextDocument("My First Document", "This is a simple text document for NLP.")
print(f"Word count: {doc.word_count()}") 
Word count: 8

Exercise 2: Extend the Text Class for Analysis

Task: Extend the TextDocument class to include a method that counts the frequency of a specific word.

Instructions:

  • Add a method called count_word_frequency(self, word) to the TextDocument class that counts how many times a specific word appears in the content.
  • Create an instance of the class and call this method with a sample word.
Show solution
class TextDocument:
    def __init__(self, title, content):
        self.title = title
        self.content = content
    
    def word_count(self):
        return len(self.content.split())
    
    def count_word_frequency(self, word):
        return self.content.lower().split().count(word.lower())

# Sample usage
doc = TextDocument("My First Document", "This is a simple text document for NLP. NLP is fun.")
print(f"Word count: {doc.word_count()}") 
print(f"Frequency of 'NLP': {doc.count_word_frequency('NLP')}")  
Word count: 11
Frequency of 'NLP': 1

Exercise 3: Create a Chat Class

Task: Create a class that represents a chat session.

Instructions:

  • Define a class called ChatSession with the following attributes:
    • messages (list to store messages)
  • Include methods to:
    • add_message(sender, message) that appends a message to the messages list.
    • get_chat_log() that returns the chat log as a list of strings formatted as “sender: message”.
  • Create an instance of the ChatSession class and demonstrate adding messages and retrieving the chat log.
Show solution
class ChatSession:
    def __init__(self):
        self.messages = []
    
    def add_message(self, sender, message):
        self.messages.append(f"{sender}: {message}")
    
    def get_chat_log(self):
        return self.messages

# Sample usage
chat = ChatSession()
chat.add_message("User", "Hello!")
chat.add_message("Chatbot", "Hi there! How can I assist you today?")
chat.add_message("User", "What is NLP?")
log = chat.get_chat_log()
print("Chat Log:")
for message in log:
    print(message)
Chat Log:
User: Hello!
Chatbot: Hi there! How can I assist you today?
User: What is NLP?
Back to top