Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In Python, implement a function average () that takes one parameter which is a s

ID: 3791450 • Letter: I

Question

In Python, implement a function average() that takes one parameter which is a string representing the name of a text file. The function should return the average length of a word in the file.

The puncutation in the file should be removed prior to determining the average length of a word in the file. For the purposes of this question the valid puncutation symbols are commas (,), periods (.), exclamation marks (!), question marks (?), semicolons (;), and colons (:). Hint: You can replace a character in a string using the replace() function. In this case, you want to replace each of the above characters by an empty string.  Hint 2: Remember, strings are immutable…    s.replace('e','q') à will replace all e characters with q. However, the string will not have changed! Instead, we need:  s = s.replace('e','q')

If the file cannot be opened the function should print a message indicating that an exception prevented further execution and should return -1.

If the file is empty, the function should return 0. (Hint: Not all if statements require an else…)

The following shows what the function would return when called on several sample files found in the zip file containing the lab template.

Files: Test your code using the files:  duplicates.txt, poppins.txt, and empty.txt.  You can find these files on the 'Resources' page of the course web site.

Hint: Remember… always spend a few minutes thinking about the problem with pen and paper before diving into the code!

avg average duplicates .txt print (avg) 5.222222222222222 avg average poppins txt print (avg) 5.170984455958549 avg average empty .txt print (avg) avg average does not exist txt') Unable to open file.

Explanation / Answer

def average(s):
    try:
        f=open(s,'r')
    except IOError:
        return 'Unable to open file'
    s=f.read()
      
    if ( len(s) == 0):
        return 0
    marks=[',','.',''',';',':','?','!']

    for i in range(len(s)):
        if s[i] in marks:
            s=s.replace(s[i],' ')

    length_list=[]
    for word in s.split():
        length_list.append(len(word))

    return sum(length_list)/len(length_list)
  

if __name__=="__main__":
    print(average('sample.txt'))
    print(average('sample2.txt'))
    print(average('sample22.txt'))
   

sample output

5.435897435897436
0
Unable to open file

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote