Hw8_Fall_2023

.pdf

School

University of California, Berkeley *

*We aren’t endorsed by this school

Course

MISC

Subject

Computer Science

Date

Dec 6, 2023

Type

pdf

Pages

2

Uploaded by DeaconBat3708

11/9/23, 9:24 AM Hw8_Fall_2023.ipynb - Colaboratory https://colab.research.google.com/drive/1_Z5Sl4gxpZUGYbcM_Ac_zvSGKs3iliPa?authuser=1#printMode=true 1/2 Objective: Gain experience with dictionaries by counting the frequency of words in a given text. Instructions: Write a function word_frequencies(text: str) -> dict that takes a string as an argument and returns a dictionary with words as keys and their frequencies as values. Convert the text to lowercase before processing. Ignore punctuations like ., ,, ?, !, and so on. Ignore common stop words like "and", "the", "is", "in", etc. Test your function with a sample text to verify its correctness. Sample Input: text = "Hello, world! The world is beautiful. Hello everyone!" Sample Output: { 'hello': 2, 'world': 2, 'beautiful': 1, 'everyone': 1 } Exercise: Word Frequencies #your code here text = "Hello, world! The world is beautiful. Hello everyone!" def word_frequencies(text): text = text.replace('.', '') text = text.replace('!', '') text = text.replace('?', '') text = text.replace(',', '') text = text.replace('(', '') text = text.replace(')', '') text_arr = text.split(' ') word_dict = {} for word in text_arr: word = word.lower()
11/9/23, 9:24 AM Hw8_Fall_2023.ipynb - Colaboratory https://colab.research.google.com/drive/1_Z5Sl4gxpZUGYbcM_Ac_zvSGKs3iliPa?authuser=1#printMode=true 2/2 if word not in word_dict: word_dict[word] = 0 word_dict[word] += 1 return word_dict print(word_frequencies(text)) {'hello': 2, 'world': 2, 'the': 1, 'is': 1, 'beautiful': 1, 'everyone': 1}
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help