Reputation: 13
I'm attempting to search through a text file and determine how many lines, vowels, consonants and numerical values/characters are in the text file. My Vowels, consonants and numerical output values aren't calculating properly, so it seems. The lines output total is correctly calculated.
ein = input("Please enter file name: ")
vowels = set("AEIOUaeoiu")
cons = set("BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwvyz")
num = set("1234567890")
count = 0
Vcount = 0
Ccount = 0
Ncount = 0
with open(ein) as ein_handle:
for line in ein_handle:
count += 1
for line in ein_handle:
if line in vowels:
Vcount += 1
elif line in cons:
Ccount += 1
elif line in num:
Ncount += 1
print("the file has",count,"lines.")
print("the file has",Vcount,"vowels.")
print("the file has",Ccount,"consonants.")
print("the file has",Ncount,"numerical characters.")
Upvotes: 0
Views: 57
Reputation: 522
here is another way:
import os
d,_ = os.path.split(__file__)
ein = input("Please enter file name: ")
vowels = "aeoiu"
cons = "bcdfghjklmnpqrstvwvyz"
num = "1234567890"
Vcount = 0
Ccount = 0
Ncount = 0
with open(d+"\\" + ein) as ein_handle:
lines = ein_handle.readlines()
for line in lines:
line = line.lower()
for v in vowels:
tmp = line
while v in tmp:
Vcount += 1
tmp = tmp[tmp.find(v)+1:]
for c in cons:
tmp = line
while c in tmp:
Ccount += 1
tmp = tmp[tmp.find(c)+1:]
for n in num:
tmp = line
while n in tmp:
Ncount += 1
tmp = tmp[tmp.find(n)+1:]
print("the file has",len(lines),"lines.")
print("the file has",Vcount,"vowels.")
print("the file has",Ccount,"consonants.")
print("the file has",Ncount,"numerical characters.")
Upvotes: 0
Reputation: 7548
the second loop should be for each character in the given line instead.
Try this one:
ein = input("Please enter file name: ")
vowels = set("AEIOUaeoiu")
cons = set("BCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwvyz")
num = set("1234567890")
count = 0
Vcount = 0
Ccount = 0
Ncount = 0
with open(ein) as ein_handle:
for line in ein_handle:
count += 1
for letter in line:
if letter in vowels:
Vcount += 1
elif letter in cons:
Ccount += 1
elif letter in num:
Ncount += 1
print("the file has", count, "lines.")
print("the file has", Vcount, "vowels.")
print("the file has", Ccount, "consonants.")
print("the file has", Ncount, "numerical characters.")
Also, the main reason you're getting 0 (instead of line count) inside the second loop is because when the first loop executes, it updates the read offset position with every iteration until it becomes at the end. So when the second loop starts, it starts from the end of the file and can't read anything.
Upvotes: 1