Computer Science, asked by substud09, 6 months ago

Write a program to read a file "new.txt" Print no. of characters in each line.

Answers

Answered by Anonymous
1

Answer:

I have a file with these words:

hey how are you

I am fine and you

Yes I am fine

And it is asked to find the number of words, lines and characters.

Below is my program, but the number of counts for the characters without space is not correct.

The number of words is correct and the number of line is correct. What is the mistake in the same loop?

fname = input("Enter the name of the file:")

infile = open(fname, 'r')

lines = 0

words = 0

characters = 0

for line in infile:

wordslist = line.split()

lines = lines + 1

words = words + len(wordslist)

characters = characters + len(line)

print(lines)

print(words)

print(characters)

The output is:

lines=3(Correct)

words=13(correct)

characters=47

I've looked on the site with multiple answers and I am confused because I didn't learn some other functions in Python. How do I correct the code as simple and basic as it is in the loop I've done?

Whereas the number of characters without space is 35 and with space is 45. If possible, I want to find the number of characters without space. Even if someone know the loop for the number of characters with space that's fine.

If you want to count the number of characters without the spaces, you have to sum up the lengths of all entries in the wordslist, because since line still contains the spaces, len(line) returns 15 for the first line, not 12.

Thank You!!

Similar questions