2

I've got this base of my code:

from tkinter import *

def clik(z=None):
    global T
    s = T.get("1.0",'end-1c')
    ## what next?

o= Tk()

T=Text(o, height=20, width=50)
T.pack()
T.bind("<Key>", clik)

o.mainloop()

Every time user will type something inside of Text widget I'm using function to gather the input. Now the goal is to see how many number and letter did he use. Spliting s and checking it with isalpha() and isalnum() does not work so great if user input would look something like ' Abs3 asdasd asd11 111 11ss'. How can I keep tracing and storing user input inside of Text widget if I want to have information about current amount of numbers and letters inside of Text widget? Thank you in advance

Derek Johnson
  • 717
  • 1
  • 5
  • 9
  • When you say "Spliting s and checking it with isalpha() and isalnum()", what are you splitting on? (whitespace?, empty string?) – bunji Apr 20 '17 at 13:55
  • Whitespace. It would work if user would only give input like: 'I am 7 years old' but if he did 'I am 7yrs old", 7yrs is neither isalnum or isalpha, – Derek Johnson Apr 20 '17 at 13:57
  • So are you counting the number of words that contain only alpha characters and the number of words that only contain digits or do you want the total count of all alphas and digits? Should the alpha count for 'I am 7 years old' be 11 or 4? – bunji Apr 20 '17 at 14:01
  • "I am 7 years old " output would be letters:11, numbers:1, same outcome for "I am 7years old" – Derek Johnson Apr 20 '17 at 14:04

2 Answers2

1

Iterate over the string.

def click(event):
    chars, nums = 0,0
    for char in T.get("1.0","end-1c"):
        if char.isalpha(): chars += 1
        elif char.isdigit(): nums += 1

    print("Characters: %d Numbers: %d"%(chars, nums))
Dashadower
  • 632
  • 1
  • 6
  • 20
1

To get the counts of alpha and digit characters (not words) don't split on whitespace, check each character individually.

s = ' Abs3 asdasd asd11 111 11ss'

alpha_count = 0
digit_count = 0
for c in s:    ## here we are looping over every character in the string
    if c.isalpha():
        alpha_count += 1
    elif c.isdigit():
        digit_count += 1

print(alpha_count, digit_count)

(14,8)
bunji
  • 5,063
  • 1
  • 17
  • 36
  • Thank you, I have one more question: if I'm using this "s = T.get("1.0",'end-1c')" it does not count first type number. So if I'm counting letter/numbers if I type inside widget 'a' it wont see it unless I hit space or another letter/number. Is there a way to get user input from the very start? – Derek Johnson Apr 20 '17 at 17:31
  • Maybe because you are `get`ing starting from index 1 not index 0. But this is a separate question and should be asked separately, not in a comment. – bunji Apr 20 '17 at 18:02
  • I did, thanks http://stackoverflow.com/questions/43526918/how-to-trace-user-input-from-first-hit-of-the-button-in-text-widget – Derek Johnson Apr 20 '17 at 18:13