In Python Write a function called howManyWordsAndSentences that takes in a strin
ID: 3749178 • Letter: I
Question
In Python
Write a function called howManyWordsAndSentences that takes in a string. Your function should return a dictionary where the keys are the order position of each SENTENCE (you may assume sentences will end with periods, exclamation points, or question marks). The data for each key should be a tuple containing the number of words in the sentence and a string containing the sentence itself (you should remove the extra spaces before or after each sentence) Your function should print out how many sentences there are in the input string. Ex: For the input string Our class string is I Love Chocolate Milk. This may seem silly. But I really do love chocolate milk!" Your dictionary would have 3 entries The first key would be 1, and the data would be 8 (number of words) and the string "Our class string is I Love Chocolate Milk." The second key would be 2, and that data would be 4 (number of words) and the string "This may seem silly". The third key would be 3, and the data would be 7 (number of words) and the string "But I really do love chocolate milk!"Explanation / Answer
def howManyWordsAndSentences( str ):
sentences=str.replace('!','.').replace('?','.').rsplit('.', 1)[0].split('.') #replace ? and ! with . and split it with delimiter '.'
noOfSentences=len(sentences) #store value of number of sentences
print "Number of sentences: ",noOfSentences #print number of sentences
dict={} #create dictionary dict
i=1 #first key value
for sentence in sentences:
noOfWords=len(sentence.replace(',',' ').replace(';',' ').lstrip().split(' ')) #replace , and ; with space and split it with delimiter ' '
list=[] #create list
list.append(noOfWords) #enter first value as number of words
list.append(sentence.lstrip()) #enter sentence without space in front or back of the sentence
tup=tuple(list) #convert list to tuple
dict[i]=tup #add tuple as data to dictionary dict with key as i
i=i+1 #increment key
return dict #return dictionary dict
def main():
str=raw_input("Enter sentences:")
dict=howManyWordsAndSentences(str)
print(dict)
if __name__ == '__main__':
main()
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.