In python, explanations help. both problems 1. Write a function numTimes) that t
ID: 3880929 • Letter: I
Question
In python, explanations help. both problems
1. Write a function numTimes) that takes a string representing a sentence and a string representing a word as a parameters and returns the number of times the word appears in the sentence. Words in the string are non-space characters separated by at least one space. Please make sure to remove any punctuation from the "sentence" before counting words. For the purposes of this question, punctuation is restricted to a comma, a semicolon, an exclamation mark, a question mark, and a period. If either parameter string is empty the function should return 0. The capitalization of the word or the sentence should not make any difference in computing the count. The function should not consider substrings when checking for the word. The following shoes several examples of how the function could be used: Python 3.62 Shell File Edit Shell Debug Options Window Help >>> numTimes'That is my favorite FAVOR: IS it yours?', 'is' >>> val - numTimes That is my favorite FAVOR: IS it yours?','Favor') >val >>>numTimes ("Testing, testing, only more TESTING!", 'testing') >>>numTimes "Testing, testing, only more TESTING!", 'test') 0 >>> val = numTimes ("Yesterday we had to find YES, because yes", 'Yes') val Ln: 33 Col: 0 2. Write a function numVowels) that takes a string representing a file name as a parameter and returns the number of vowels (both upper- and lowercase) that appear in the file. For the purposes of this question a vowel is one of a, e, i, o, or u. The following shows how the function would behave for several sample files that are included in the zip file with the assignment template Python 3.62 Shell File Edit Shel Debug Options Window Help >num - numVowels'vovels.txt' num >>numVowelsexample.txt') 32 >count - numVowels(' empty.txt' Count >>> numVowels'poppins.txt' 418 Ln: 51 Col: 4Explanation / Answer
The code for 1 is
using regular expressions
import re
def numTimes(s,s1):
s = re.sub(r'[^ws]','',s)# this stores the string with punctuation removed
return s.count(s1)# returns the number of non-overlapping occurence of s1 in s
Q2
def numVowels(s):
f=open(s,'r')
content=f.read()
st="aieouAEIOU"
count=0
for i in content:
if i in st:
#if i i.e.the char in content is same as anthing in
#in the string then this causes count to increase by 1
count=count+1
return count
print(numVowels('a.txt'))
Do give a thumbs up
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.