Question

In: Computer Science

I am trying to make a program in Python that opens a file and tells you...

I am trying to make a program in Python that opens a file and tells you how many lines, vowels, consonants, and digits there are in the file.

I got the print out of lines, digits, and consonants, but the if statement I made with the vowels list isn't recognizing them. How can I make the vowels go through the if statement with the list? Am I using the wrong operator?

Here is my program

#Assignment Ch7-1
#This program takes a user input file name and returns how many lines, vowels,
#consonants and digits are in the
while True:
    vowel = 0
    cons = 0
    digit = 0
    count = 0
    vlist = ('aeiou')
    try:
        fname = input('Please enter the file name to open:')
        fhand = open(fname)
  
        for line in fhand:
            count += 1
            for ch in line:
                if ch.isdigit():
                    digit +=1
                elif ch.isalpha():
                    if ch is vlist:
                        vowel += 1
                    else:
                        cons += 1
              
          
        print('This is the vowels: ',vowel)
        print('These are the digits: ',digit)
                  
        print('These are the consanants: ',cons)
        print('These are the lines: ',count)
                      
        ans = input("Do you want try again y/n: ") #asking user to contiune
        
        if ans == 'y' or ans == 'Y':
            continue
        else:
            if ans == 'n' or ans == 'N':
                print('Goodbye')
                break   
    except:
        print('File cannot be opened:', fname)
        continue
          
          
  

Solutions

Expert Solution

Please find the fixed code below :

while True:
   vowel = 0
   cons = 0
   digit = 0
   count = 0
   vlist = ('aeiou')
   try:
       fname = input('Please enter the file name to open:')
       fhand = open(fname)
       for line in fhand:
           count += 1
           for ch in line:
               if ch.isdigit():
                   digit +=1
               elif ch.isalpha():
                   if ch in vlist:
                       vowel += 1
                   else:
                       cons += 1
          
       print('This is the vowels: ',vowel)
       print('These are the digits: ',digit)
              
       print('These are the consanants: ',cons)
       print('These are the lines: ',count)
                  
       ans = input("Do you want try again y/n: ") #asking user to contiune
      
       if ans == 'y' or ans == 'Y':
           continue
       else:
           if ans == 'n' or ans == 'N':
               print('Goodbye')
               break   
   except:
       print('File cannot be opened:', fname)
       continue

Sample Output :

Sample File:

Sample Output:

Please comment below if you have any queries.
Please do give a thumbs up if you liked the answer thanks :)


Related Solutions

this is my code in python I am trying to open a file and then print...
this is my code in python I am trying to open a file and then print the contents on my console but when i run it nothing prints in the console def file_to_dictionary(rosterFile): myDictionary={}    with open(rosterFile,'r') as f: for line in f: myDictionary.append(line.strip()) print(myDictionary)             return myDictionary    file_to_dictionary((f"../data/Roster.txt"))      
I am trying to create a program that reads from a csv file and finds the...
I am trying to create a program that reads from a csv file and finds the sum of total volume in liters of liquor sold from the csv file by county and print that list out by county in descending order. Currently my program runs and gives me the right answers but it is not in descending order. I tried this:     for county, volume in sorted(sums_by_volume.items(), key=lambda x: x[1], reverse=True):         index +=1         print("{}. {} {:.2f}".format(county, sums_by_volume[county]))      When I run...
I am trying to make a Risk Management tool in Python. I have it partially started....
I am trying to make a Risk Management tool in Python. I have it partially started. The scenario is that the Project Manager needs to be able to log on and enter information ( the required information is located in the code). I then need to capture that data and store it in an array with the ability to call back and make changes if necessary. Could you please help me out and explain what was done? Current code: Start...
I am having a trouble with a python program. I am to create a program that...
I am having a trouble with a python program. I am to create a program that calculates the estimated hours and mintutes. Here is my code. #!/usr/bin/env python3 #Arrival Date/Time Estimator # # from datetime import datetime import locale mph = 0 miles = 0 def get_departure_time():     while True:         date_str = input("Estimated time of departure (HH:MM AM/PM): ")         try:             depart_time = datetime.strptime(date_str, "%H:%M %p")         except ValueError:             print("Invalid date format. Try again.")             continue        ...
1)  Write a python program that opens a file, reads all of the lines into a list...
1)  Write a python program that opens a file, reads all of the lines into a list of strings, and closes the file. Use the Readlines() method. Test your programing using the names.txt file provided. 2) Convert the program into a function called loadFile, that receives the file name as a parameter and returns a list of strings. 3) Write a main routine that calls loadFIle three times to load the three data files given into three lists. Then choose a...
write a program in c++ that opens a file, that will be given to you and...
write a program in c++ that opens a file, that will be given to you and you will read each record. Each record is for an employee and contains First name, Last Name hours worked and hourly wage. Example; John Smith 40.3 13.78 the 40.3 is the hours worked. the 13.78 is the hourly rate. Details: the name of the file is EmployeeNameTime.txt Calculate the gross pay. If over 40 hours in the week then give them time and a...
Working with Python. I am trying to make my code go through each subject in my...
Working with Python. I am trying to make my code go through each subject in my sample size and request something about it. For example, I have my code request from the user to input a sample size N. If I said sample size was 5 for example, I want the code to ask the user the following: "Enter age of subject 1" "Enter age of subject 2" "Enter age of subject 3" "Enter age of subject 4" "Enter age...
This is my code for python. I am trying to do the fourth command in the...
This is my code for python. I am trying to do the fourth command in the menu which is to add an employee to directory with a new phone number. but I keep getting error saying , "TypeError: unsupported operand type(s) for +: 'dict' and 'dict". Below is my code. What am I doing wrong? from Lab_6.Employee import * def file_to_directory(File): myDirectory={}       with open(File,'r') as f: data=f.read().split('\n')    x=(len(data)) myDirectory = {} for line in range(0,199):      ...
This is for Python programming, and I am trying to use 2 for loops to ask...
This is for Python programming, and I am trying to use 2 for loops to ask a slaesperson how many of 5 different items they sold, then the program is to calculate the total dollar amount sold. Formatting and all that aside, I am having an issue with the loops not stepping through the 2 lists at the same time. The first loop is taking all 5 entered quantities times the price of the first item, and then all 5...
This is in Python, I am trying to create a new window to print the data...
This is in Python, I am trying to create a new window to print the data to screen, it prints fine in the terminal. I know this is a small segment of my code and its the only portion I am having a problem with. I was wondering if anyone can see what my problem may be. The current issue is NameError: name 'fltVal' is not defined and AttributeError: 'PressureGUI' object has no attribute 'r_count' Any help would be appreciated...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT