logo elektroda
logo elektroda
X
logo elektroda

[Python] Count and Display Numbers and Words Per Line in a Multi-Line Input Text

baklabak 16104 2
ADVERTISEMENT
Treść została przetłumaczona polish » english Zobacz oryginalną wersję tematu
  • #1 7883366
    baklabak
    Level 10  
    Hello.

    I have a program that counts numbers and words in a sentence. I have such a problem with this program: it gives results for one line (the first line we enter and we exit the program) or for the last one when we enter more lines.


    
    
    while 1:
           try: znaki= raw_input().split()
           except EOFError: break
           liczby = 0
           slowa = 0
           for i in range(len(znaki)):
            if znaki[i].isdigit() == 1: liczby += 1
            else:
             slowa += 1
    print liczby,  slowa
    
    




    Will anyone help me to rewrite this program to display the number of numbers and words for each entered line after finishing typing?
  • ADVERTISEMENT
  • #2 7884778
    skynet_2
    Level 26  
    Python is indented to make the code readable.

    znaki = list()
    while 1: 
    	try:
    		# ^D ^Z
    		znaki.append(raw_input())
    	except EOFError:
    		break 
    
    liczby = 0 
    slowa = 0 
    for linia in znaki:
    	linia = linia.split()
    	for slowo in linia:
    		if slowo.isdigit():
    			liczby += 1
    		else:
    			slowa += 1
    
    print liczby,  slowa


    you just have to go to a new line before you finish typing.
  • #3 7886818
    bekcham
    Level 11  
    
    while True:
            try:
                    znaki = raw_input()
            except EOFError:
                    break
            
            liczby, slowa = 0, 0
            for s in znaki.split():
                    if s.isdigit():
                            liczby += 1
                    elif s.isalpha():
                            slowa += 1
            print "%d %d" % (liczby, slowa)
    
ADVERTISEMENT