Exercise: Functions

Exercise 1: Function to Count Words

Task: Write a function called count_words(text) that takes a string of text as input and returns the number of words in it.

Instructions:

  • Define a function count_words(text).
  • Split the text into words using split().
  • Return the number of words.
  • Test the function with different sentences.
Show solution
def count_words(text):
    words = text.split()
    return len(words)

sentence = "Natural language processing is fun!"
print(count_words(sentence))  # Output: 5
5

Exercise 2: Function to Convert Text to Lowercase

Task: Write a function called convert_to_lowercase(text) that takes a string of text and returns it with all characters in lowercase.

Instructions:

  • Define a function convert_to_lowercase(text).
  • Use the .lower() method to convert the text to lowercase.
  • Return the modified text.
  • Test the function with various sentences.
Show solution
def convert_to_lowercase(text):
    return text.lower()

text = "NLP Can Be Challenging But REWARDING!"
print(convert_to_lowercase(text))  # Output: "nlp can be challenging but rewarding!"
nlp can be challenging but rewarding!

Exercise 3: Function to Replace a Word

Task: Create a function called replace_word(text, old_word, new_word) that takes a string of text, a word to be replaced, and the new word, then returns the modified text.

Instructions:

  • Define a function replace_word(text, old_word, new_word).
  • Use the .replace() method to replace old_word with new_word.
  • Return the modified text.
  • Test the function with different sentences.
Show solution
def replace_word(text, old_word, new_word):
    return text.replace(old_word, new_word)

text = "Python is fun, and learning Python is rewarding."
print(replace_word(text, "Python", "NLP"))  # Output: "NLP is fun, and learning NLP is rewarding."
NLP is fun, and learning NLP is rewarding.

Exercise 4: Word Frequency Counter

Task: Create a function to count the frequency of a specific word in a given sentence.

Instructions:

  • Define a function called word_frequency(sentence, word) that takes a string parameter sentence and a string parameter word.
  • Inside the function, use the split() method to break the sentence into words, then count how many times word appears in the list. Hint: Use the list method .count().
  • Return the count.
  • Call the function with a sample sentence and word, then print the result.
Show solution
def word_frequency(sentence, word):
    words = sentence.split()
    return words.count(word)

# Sample usage
sentence = "NLP is great and NLP is fun"
word = "NLP"
result = word_frequency(sentence, word)
print(f"The word '{word}' appears {result} times.")  # Output: The word 'NLP' appears 2 times.
The word 'NLP' appears 2 times.

Exercise 5: Sentence Reversal

Task: Write a function that reverses the words in a sentence.

Instructions:

  • Define a function called reverse_sentence(sentence) that takes a string parameter sentence.
  • Inside the function, split the sentence into words, reverse the order of the words, and then join them back into a single string.
  • Return the reversed sentence.
  • Call the function with a sample sentence and print the result.
Show solution
def reverse_sentence(sentence):
    words = sentence.split()
    reversed_words = words[::-1]
    return ' '.join(reversed_words)

# Sample usage
sentence = "Natural Language Processing is fun"
result = reverse_sentence(sentence)
print("Reversed sentence:", result)  # Output: Reversed sentence: fun is Processing Language Natural
Reversed sentence: fun is Processing Language Natural

Exercise 6: Remove Punctuation

Task: Create a function to remove punctuation from a given string.

Instructions:

  • Define a function called remove_punctuation(text) that takes a string parameter text.
  • Inside the function, use a loop or list comprehension to create a new string that only includes alphanumeric characters and spaces. Hint: You can the string methods .isalnum() and .ischar().
  • Return the cleaned text.
  • Call the function with a sample string (e.g., “NLP is great! Isn’t it?”) and print the result.
Show solution
def remove_punctuation(text: str):
    # Use list comprehension to filter out punctuation
    cleaned_text = ''.join(char for char in text if char.isalnum() or char.isspace())
    return cleaned_text

# Sample usage
text = "NLP is great! Isn't it?"
result = remove_punctuation(text)
print("Cleaned text:", result)  # Output: Cleaned text: NLP is great Isnt it
Cleaned text: NLP is great Isnt it

Exercise 7: Average Word Length

Task: Write a function to calculate the average length of words in a sentence.

Instructions:

  • Define a function called average_word_length(sentence) that takes a string parameter sentence.
  • Inside the function, split the sentence into words, calculate the average length of the words, and return the result.
  • Call the function with a sample sentence (e.g., “Natural Language Processing is powerful”) and print the average length.
Show solution
def average_word_length(sentence):
    words = sentence.split()
    if len(words) == 0:
        return 0
    total_length = sum(len(word) for word in words)
    return total_length / len(words)

# Sample usage
sentence = "Natural Language Processing is powerful"
result = average_word_length(sentence)
print("Average word length:", result)  
Average word length: 7.0
Back to top