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.
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.
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
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))