Count the total number of words from stdin

Question:

I have to read a text file name (the text file is already on my computer), open it, read it, and print the total number of words.

Here is what I’ve tried so far:

import sys

file = sys.stdin
    
with open(file) as f: # also tried using open(file, 'r', encoding='utf-8')
    data = f.readlines()
    words = data.split()
    
    no_of_words = 0
    for word in words:
        no_of_words += 1
        print(no_of_words)

But when I try to run it, it shows the following error:

"with open(file) as f:
TypeError: expected str, bytes or os.PathLike object, not TextIOWrapper"
Asked By: Vyshakh

||

Answers:

Personally, if I was just capturing input in python I would use this.

inp = input("Type something:")
print(len(inp.split()))

If you have your heart set on doing it with that. You could do this…

import sys

file = sys.stdin
count = 0
for word in file.readline().split():
    count += 1
    
print(count)

I imagine there’s a better way if you need to use sys.stdin but that does work.

EDIT: Figured out a better way and found a link.
Though a similar answer can be found here. Python: Splitting a string into words, saving separators

Answered By: Ash

You need to read the file name using input(), then test if the file name exists, and just read and split it into words to count them.

Something like this is a good starting point:

from pathlib import Path

text_file = Path(input('Type the file name: '))

if text_file.exists() and text_file.is_file():
    print(f'{text_file} has', len(text_file.read_text().split()), 'words')
else:
    print(f'File not found: {text_file}')
Answered By: accdias
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.