Search code examples
pythonfor-loopwith-statementtxt

Reading and performing actions from files contents


So I am trying to do this lab that gives you a bunch of information from a .txt file. Each line contains some letters and numbers and I am supposed to write code to answer 5 questions from each line of the text: print the 5 letter sequence using lowercase letters, print if the 5 letter sequence contains any vowels, print the volume of a sphere that has the radius of the first number, print if the remaining 3 numbers can make a triangle, and print the average of the last 3 numbers.

Here are 3 lines of the Lab5_Data.txt:

WLTQS 13 64 23 99

ZNVZE 82 06 53 82

TMIWB 69 93 68 65

Here is the expected output of those 3 lines:

The string in lowercase is wltqs

WLTQS does not contain any vowels

The volume of the sphere with radius 13 is 9202.7720799157

64, 23, 99 cannot make a triangle.

The average of 64, 23, 99 is 62.0

The string in lowercase is znvze

ZNVZE contains vowels

The volume of the sphere with radius 82 is 2309564.8776326627

6, 53, 82 cannot make a triangle.

The average of 06, 53, 82 is 47.0

The string in lowercase is tmiwb

TMIWB contains vowels

The volume of the sphere with radius 69 is 1376055.2813841724

93, 68, 65 can make a triangle

The average of 93, 68, 65 is 75.33333333333333

Here is my code so far:

with open('Lab5_Data.txt', 'r') as my_file:
    for line in my_file:
        data = line.split()
        print(line)

for line in my_file:
    line = line[0:5].lower()
    print('Thr string in lowercase is', line)

for i in my_file:
    if(i== 'A' or i== 'E' or i== "I" or i== 'O' or i== 'U'):
        print('contains vowels')
    else:
        print('does not contain any vowels')

I am having trouble with getting each line to split so that when I print the output it shows each of the answers together with the same line. In addition, I am having difficulty trying to get the functions for each of these answers without making one huge for loop. If anybody has any input to help me out, it would be greatly appreciated!


Solution

  • The main idea here is that you can iterate your file line by line, split the line into usable data chunks, and then pass the correct chunk to different functions. It will be a single large loop, but each individual calculation will be done in separate functions, so that helps with modularity.

    Now, there are many ways to go for the functions, and how to handle the output and printing: you could avoid printing inside the functions; you could return the entire answer string; you could just return the calculated value instead of a text string; you could handle the strings completely outside; etc. I think you get the idea.

    I'll leave that level of customization to your preference. I didn't want to overly complicate the code, so I kept is as simple and reasonably readable as possible, sometimes sacrificing some more pythonic ways.

    # Here the functions that will be used later in the main loop
    # These functions will calculate the answer and produce a string
    # Then they will print it, and also return it
    
    def make_lowercase(s):
        answer = s.lower()
        print(answer)
        return answer
    
    
    def has_vowels(word):
        # For each vowel, see if it is found in the word
        # We test in lowercase for both
        answer = 'Does not contain vowels'
        for vowel in 'aeiou':
            if vowel in word.lower():
                answer = 'Contains vowels'
                break
        print(answer)
        return answer
    
    
    def calculate_sphere_volume(radius):
        # Remember to convert radius from string to number
        import math
        volume = 4.0/3.0 * math.pi * float(radius)**3
        answer = "The volume of the sphere with radius {} is {}".format(radius, volume)
        print(answer)
        return answer
    
    
    def check_possible_triangle(a1, b1, c1):
        # Remember to convert from string to number
        a = float(a1)
        b = float(b1)
        c = float(c1)
        answer = '{}, {}, {} can make a triangle'.format(a1, b1, c1)
        if (a + b <= c) or (a + c <= b) or (b + c <= a):
            answer = '{}, {}, {} cannot make a triangle'.format(a1, b1, c1)
        print(answer)
        return answer
    
    
    def calculate_average(a1, b1, c1):
        # Remember to convert from string to number
        a = float(a1)
        b = float(b1)
        c = float(c1)
        average = (a + b + c) / 3
        answer = 'The average of {}, {}, {} is {}'.format(a1, b1, c1, average)
        print(answer)
        return answer
    
    with open('Lab5_Data.txt', 'r') as my_file:    
        for line in my_file:
            # if you split each line, you get the individual elements
            # you can then group them appropriately, like so:
            # word: will contain the 5 letter string
            # radius: will be the first number, to be used for the sphere
            # a,b,c will be the three numbers to check for triangle
            # Important: THESE ARE ALL STRINGS!
            word, radius, a, b, c = line.split()
    
            # Now you can just use functions to calculate and print the results.
            # You could eliminate the prints from each function, and only use the
            # return results that will be combined in the end.
    
            # Lowercase:
            ans1 = make_lowercase(word)
    
            # Does this word have vowels?
            ans2 = has_vowels(word)
    
            # Calculate the sphere volume
            ans3 = calculate_sphere_volume(radius)
    
            # Check the triangle
            ans4 = check_possible_triangle(a, b, c)
    
            # Calculate average
            ans5 = calculate_average(a, b, c)
    
            # Now let's combine in a single line
            full_answer = '{} {} {} {} {}'.format(ans1, ans2, ans3, ans4, ans5)
            print(full_answer)