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

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        ...
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):      ...
I am trying to write a UDP socket program in which there is a server program...
I am trying to write a UDP socket program in which there is a server program and a client program. This is what I have but I can't figure out where I am going wrong. This is the input and expected output: > gcc udpclient.c –o clientout > gcc udpserver.c –o serverout > ./serverout 52007 ‘to celebrate’ & > ./clientout odin 52007 ‘Today is a good day’ Today is a good day to celebrate //UDP echo client program #include #include...
I am trying to create a makefile for the following program in Unix. The C++ program...
I am trying to create a makefile for the following program in Unix. The C++ program I am trying to run is presented here. I was wondering if you could help me create a makefile for the following C++ file in Unix and show screenshots of the process? I am doing this all in blue on putty and not in Ubuntu, so i don't have the luxury of viewing the files on my computer, or I don't know how to...
This is in Python I am getting an error when I run this program, also I...
This is in Python I am getting an error when I run this program, also I cannot get any output. Please help! #Input Section def main(): name=input("Please enter the customer's name:") age=int(input("Enter age of the customer: ")) number_of_traffic_violations=int(input("Enter the number of traffic violations: ")) if age <=15 and age >= 105: print('Invalid Entry') if number_of_traffic_violations <0: print('Invalid Entry') #Poccessing Section def Insurance(): if age < 25 and number_of_tickets >= 4 and riskCode == 1: insurancePrice = 480 elif age >=...
Can you write this program, but in python, I just wanna see what am I doing...
Can you write this program, but in python, I just wanna see what am I doing wrong. thank you Instructions: The Gas-N-Clean Service Station sells gasoline and has a car wash. Fees for the car wash are $1.25 with a gasoline purchase of $10.00 or more and $3.00 otherwise. Three kinds of gasoline are available: regular at $2.89, plus at $3.09, and super at $3.39 per gallon. User Request: Write a program that prints a statement for a customer. Analysis:...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT