-5

The code should read the text from the file "input.txt" and then count the number of letters and words in each line, and then write the output to a new file named "output.txt"

I need help with writing the code for the above question.

ROHIT K F
  • 91
  • 3
  • 9
  • 3
    Please read [Open Letter to Students with Homework Problems](https://softwareengineering.meta.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems). You can't just dump your problem statement here and expect us to do it for you. – Anwarvic Jun 15 '20 at 08:28

2 Answers2

1
import sys

fname = sys.argv[1]
lines = 0
words = 0
letters = 0

for line in open(fname):
    lines += 1
    letters += len(line)

    pos = 'out'
    for letter in line:
        if letter != ' ' and pos == 'out':
            words += 1
            pos = 'in'
        elif letter == ' ':
            pos = 'out'

print("Lines:", lines)
print("Words:", words)
print("Letters:", letters)

try this and let me know

jay las
  • 45
  • 7
0

There's no detail information about what a word, so assume that any item seprated by space will be a word here. Any other special chars will also be a word if they seperate by space.

Try this:

with open('input.txt', 'rt') as f:
    lines = f.readlines()

result = []
for line in lines:
    length = len(line)
    words = len(line.strip().split())
    result.append(', '.join([str(length), str(words)]))

with open('output.txt', 'wt') as f:
    f.write('\n'.join(result))
Jason Yang
  • 11,284
  • 2
  • 9
  • 23