Python Forum

Full Version: sys.stdin to do a word count based on user entry
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all

I have been using the sys module's stdinput to take input from the user until they enter the keyword 'submit'. Once this happens the dictionary would have stored the key:value pairs for what has been inputted up to this point.
The key:value pairs should print to the user.

The issue I am having is that I can't stop the std input with the keyword 'submit', curious why this is?

import sys
dictionary_words = {}
for line in sys.stdin:
    for word in line.split():
        if word == 'submit':
            break
        else:
            dictionary_words[word] = dictionary_words.get(word,0) + 1
for key,value in dictionary_words.items():
    print(key,value)
If its of any help, when I compile this py file, I run it in a linux terminal.

Much appreciated

P.S Unfortunately do have to use stdin :)
You may try to .strip() any non-printable chars from word,
before you test it. You never know.

Paul
(Jul-19-2020, 09:44 AM)DPaul Wrote: [ -> ]You may try to .strip() any non-printable chars from word,
before you test it. You never know.

Paul


hmm :( I added .strip() in the for loop, but still no good... when I type "submit" it just keeps accepting standard input and does not break the loop..


import sys
dictionary_words = {}
for line in sys.stdin:
    for word in line.strip().split():
        if word == 'submit':
            break
        else:
            dictionary_words[word] = dictionary_words.get(word,0) + 1
for key,value in dictionary_words.items():
    print(key,value)
Am I right in doing a nested for loop, since I have to capture whats in the stdin first and then break up each line by words?
break takes you out of the inner loop, but you are still stuck in the outer loop. An easy way to break out of both is make this a function and use return.
def get_word_count():
    count = {}
    for line in sys.stdin:
        for word in line.split():
            if word == 'submit':
                return count
            count[word] = count.get(word,0) + 1

for key,value in get_word_count().items():
    print(key,value)
I see this a lot and it makes me wonder where it comes from. There is no reason to for the else in this code:
        if word == 'submit':
            break
        else:  # Does nothing!
            dictionary_words[word] = dictionary_words.get(word,0) + 1
If the word is 'submit' it will break out of the loop and not update the word count. If the word is not submit it will update the word count in the dictionary. The code does the same thing with or without the else.