There Is No Spoon There Is No Spoon - 1 month ago 11
Python Question

Retrieving every 5th character from a file using a for loop only, no readlines

So here is the following problem that I need to do for this class, I could do it easily but we are not allowed to use readline or read, only a for loop:


b. Write a program that takes two filenames from a user – one for
input (we will use poem.txt and suess.txt as test files) and one for
output. Then the program reads the specified input file and creates
the new output file that contains every fifth character from the input
file only if that character is a letter. In addition, the character
should be uppercase if it is a vowel, and lowercase if it is a
consonant. Finally, the program should output statistics for the
altered text, including:

• The number of characters • The number of consonants • The number of
vowels

For example, if the input file contains:

Do you like green eggs and ham? I like them, Sam I am! Do you like
green eggs and ham, Sam? Do you like them, Sam I am?


then the output file should be: OkEgnmltIOkEgnmmltI

The number of characters:
19 The number of consonants: 13 The number of vowels: 6


Here's what I got so far (ignore file placeholders):

#init vars
vowels = 'aeiou'
cons = 'bcdfghjklmnpqrstvwxyz'
noVowels = 0
noCons = 0
noChars = 0
i = 0

#Get input and output files
#usrIn = input("Input File: ")
#usrOut = input("Output File: ")

#File Manage
fi = open('suess.txt', 'r')
fo = open('test.txt', 'w')

#For loop
for line in fi:
if (line[i+4].lower() in vowels):
noVowels += 1
fo.write(line[i+4].upper())
elif (line[i+4].lower() in cons):
noCons += 1
fo.write(line[i+4].lower())




#Output stats
noChars = noCons + noVowels
print("The number of characters: {}".format(noChars))
print("The number of consonants: {}".format(noCons))
print("The number of vowels: {}".format(noVowels))

#close files
fi.close()
fo.close()


I've tried messing around with incrementing 'i' but it produces false output, which I guess is because it is only increasing 'i' after the line is already read, which obviously is wrong. I need it to get every 5th char in the line, and then start over at the 5th character for next line.
Please Help!

Answer

You can use range function with for loop:

text = "Do you like green eggs and ham? I like them, Sam I am! Do you like green eggs and ham, Sam? Do you like them, Sam I am?"
transform = ''

for l in range(4, len(text), 5):
    transform += text[l]

#remove spaces (as your example).
transform = transform.replace(' ', '')
Comments