Question

Part 1. Write a program that takes a string as input, strips whitespace and punctuation from...

Part 1. Write a program that takes a string as input, strips whitespace and punctuation from the words, and converts them to lowercase.

Hint: The string module provides strings named whitespace, which contains space, tab, newline, etc., and punctuation which contains the punctuation characters. Let’s see if we can make Python swear:

>>> import string
>>> print string.punctuation 
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Also, you might consider using the string methods strip, replace and translate (Chapter 2 of "Introducing Python" is a great reference for this).

Part 2. Modify the program from part 1 to count the total number of words in the string, and the number of times each word is used. Use a dictionary to store the frequency of each word. Your data structure should look something like:

Part 3. Modify the program from the previous exercise so it calculates and prints:

  • The top 20 most frequently used words in a given string. For each of those words, it should print the frequency and the percentage chance that the word will occur. You may want to research techniques to accomplish this online, it isn't straightforward.
  • The total number of words in the string
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Part 1

import string

def stripStr(s):

   for whitespace in string.whitespace:   #removes all whitespaces from string.
       s = s.replace(whitespace,'')

   for punctuation in string.punctuation:   #removes all punctuations
       s = s.replace(punctuation,'')

   s = s.lower()    #makes all the aphabets to lower case.    return s
s = input('Enter string: ')
s = stripStr(s)       # function strips whitespaces, punctuations and converts to lower.
print(s)

Part 2

import string

def stripStr(s):

   for whitespace in string.whitespace:   #removes all whitespaces from string.
       if whitespace != ' ':
           s = s.replace(whitespace,'')

   for punctuation in string.punctuation:   #removes all punctuations
       s = s.replace(punctuation,'')

   s = s.lower()    #makes all the aphabets to lower case.

   return s


s = input('Enter string: ')
s = stripStr(s)       # function strips whitespaces, punctuations(except space) and converts to lower.
words = s.split()   # splits string into a list of words

counts = dict()       #dictionary to count word frequency
for word in words:
   if word not in counts:
       counts[word] = 1   #if word is not present enters word in dictionary
   else:
       counts[word] += 1   #if word is present increments frequency by 1

print(counts)

Part 3

import string

def stripStr(s):

   for whitespace in string.whitespace:   #removes all whitespaces from string.
       if whitespace != ' ':
           s = s.replace(whitespace,'')
   for punctuation in string.punctuation:   #removes all punctuations
       s = s.replace(punctuation,'')
   s = s.lower()    #makes all the aphabets to lower case.
   return s

def calcProb(counts):
   tup = list(counts.items())       #creates a tuple (word,frequency) from the dictionary
   tupR = list()                   #creates a tuple (frequency,word) from the tuple
   totalWords = 0
   i = 0

   for word,freq in tup:
       tupR.append((freq,word))
       totalWords = totalWords + freq      

   tupR.sort(reverse=True)           #sorts tuple by increasing frequency

   prb = list()

   for freq,word in tupR:
       if i == 20:
           break
       prb.append((freq/totalWords)*100)   #stores probability in a list
       i += 1

   i = 0
   for freq,word in tupR:
       if i == 20:
           break
       print(word,'\tfrequency:',freq,'\tprobability:',prb[i])
       i += 1


s = input('Enter string: ')
s = stripStr(s)       # function strips whitespaces, punctuations(except space) and converts to lower.
words = s.split()   # splits string into a list of words

counts = dict()       #dictionary to count word frequency
for word in words:
   if word not in counts:
       counts[word] = 1   #if word is not present enters word in dictionary
   else:
       counts[word] += 1   #if word is present increments frequency by 1
      
calcProb(counts)   #calculates probability

Add a comment
Know the answer?
Add Answer to:
Part 1. Write a program that takes a string as input, strips whitespace and punctuation from...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • Write a Python program stored in a file q6.py that takes a text (without punctuation) as...

    Write a Python program stored in a file q6.py that takes a text (without punctuation) as input and prints the number of occurrences of each word. Your program is case-insensitive, meaning that uppercase and lowercase of the same letter is considered the same. Printing should be done in decreasing order of the number of occurrences. If several words have the same number of occurrences, they should be printed in alphabetical order. A new line must be printed between the words...

  • This program is in python and thanks fro whoever help me. In this program, you will...

    This program is in python and thanks fro whoever help me. In this program, you will build an English to Hmong translator program. Hmong is a language widely spoken by most Southeast Asian living in the twin cities. The program lets the user type in a sentence in English and then translate it to a Hmong sentence. The program does not care about grammar or punctuation marks. That means your program should remove punctuation marks from the English words before...

  • Write a program IN PYTHON that checks the spelling of all words in a file. It...

    Write a program IN PYTHON that checks the spelling of all words in a file. It should read each word of a file and check whether it is contained in a word list. A word list available below, called words.txt. The program should print out all words that it cannot find in the word list. Requirements Your program should implement the follow functions: main() The main function should prompt the user for a path to the dictionary file and a...

  • Program In Assembly For this part, your MAL program must be in a file named p5b.mal....

    Program In Assembly For this part, your MAL program must be in a file named p5b.mal. It must have at least one function in addition to the main program. For the purposes of Part (b), you may assume the following 1. Any line of text typed by a user has at most 80 characters including the newline character. 2. A whitespace character refers to a space, a tab or the new line character. 3. A word is any sequence of...

  • Write a Python program to read lines of text from a file. For each word (i.e,...

    Write a Python program to read lines of text from a file. For each word (i.e, a group of characters separated by one or more whitespace characters), keep track of how many times that word appears in the file. In the end, print out the top twenty counts and the corresponding words for each count. Print each value and the corresponding words, in alphabetical order, on one line. Print this in reverse sorted order by word count. You can assume...

  • For Python [25 pts] Write the method divisorList(aList, divisor) that takes in a list with elements...

    For Python [25 pts] Write the method divisorList(aList, divisor) that takes in a list with elements of any data type and a divisor which is in the form of an integer. The output is a sorted list of only the integers that are divisible by the divisor. Example: divisorList([1, 1, 12, 'a', 90, 34], 2) will return [12, 34, 90] since 12, 90, and 34 are all divisible by two. Note that the returned list is sorted from smallest to...

  • Using C++ programming. Write a program that takes a string of input from the user and...

    Using C++ programming. Write a program that takes a string of input from the user and separates the string of words based on the premise that the string contains words whose first letter is uppercase. Then, display the phrase (or sentence) to a string in which the words are separated by spaces and only the first word of the phrase starts with an uppercase letter. For example, if the user enters "IAmTheTeacher", then the program would display: "I am the...

  • In python please. Write a program that reads whitespace delimited strings (words) and an integer (freq)....

    In python please. Write a program that reads whitespace delimited strings (words) and an integer (freq). Then, the program outputs the strings from words that have a frequency equal to freq in a case insensitive manner. Your specific task is to write a function wordsOfFreqency(words, freq), which will return a list of strings (in the order in which they appear in the original list) that have a frequency same as the function parameter freq. The parameter words to the function...

  • Question 2 Write a program that will read in a line of text up to 100...

    Question 2 Write a program that will read in a line of text up to 100 characters as string, and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by whitespace, a period, a comma, or the beginning or end of the line. You can assume that the input consists entirely of letters, whitespace, commas, an<d periods. When...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT