user2254554
user2254554

Reputation: 13

How to count how many words are in a text string inputted by the user in python

I was wondering if anybody could help; I'm quite new to python.

I'm currently creating a tool which analyses the text inputted by a user and shows which feedback to which list that phrase belongs to.

So far the programme is on an infinite loop and counts how many expressions have been entered all together and then how many times something has occurred in a certain list.

if text in access:
    accessno +=1
    counter +=1
    print ('This could be classed as speech act 1: Access')
    print ("number of access hits ", accessno)
    print ("number of total hits ", counter)

So my question is this: how does one also get the programme to count how many words are in a sentence inputted by the user?

Any help would be much appreciated!

Upvotes: 1

Views: 6631

Answers (2)

Inbar Rose
Inbar Rose

Reputation: 43457

You can do it in the following simple way.

s = input()
# input() is a function that gets input from the user
len(s.split())
# len() checks the length of a list, s.split() splits the users input into a word list.

Links:

input() len() split()


Example:

>>> s = input()
"hello world"
>>> s
'hello world'
>>> s.split()
['hello', 'world']
>>> len(s.split())
2

Bonus: Do it all in one line!

print('You wrote {} words!'.format(len(input("Enter some text, I will tell you how many words you wrote!: ").split())))

Upvotes: 3

Hayden
Hayden

Reputation: 229

name = input ()
print len(name)

Upvotes: -1

Related Questions