+ 3
I want to count the words in a text
Hello! I want to count the words in a text, but I don’t know who to do it, can someone help me please, Thank you! https://code.sololearn.com/cr55uA6N8JV3/?ref=app
9 ответов
+ 5
+ 3
print(len(input().split()))
+ 3
Jayakrishna🇮🇳
If you assume that words can contain any digit/symbol, then in the example used by Ƥŕᥲ七Ꮍųꗟ♄ ℜᥲᒎ and also included in code of Alejandra b contains symbols like,
, ? .
So, I assume that OP is saying to omit these things. But, I may be wrong...
+ 2
first you must split the string, then get its length (number of items in an array)
use these key words
len()
split()
+ 1
#your way by function :
txt = "Whatever Comes Out Of These Gates, We have Got A Better Chance Of Survival If We Work Together. Do You Understand? If We Stay Together, We Survive"
def count_words(txt):
count = 0
for i in txt.split() :
count+=1
return count
print(count_words(txt))
+ 1
# The `split` method wouldn't work if in case, the word is like,
sentence = "I have 9 $ in my pocket - A guy"
# In that case, you could use,
import re
matches = re.findall(r"[a-zA-Z]+", sentence)
print(len(matches))
# If you want the whole list, then
print(list(matches))
+ 1
Jayakrishna🇮🇳
You can do `count += i.isalpha()` instead of `count += 1`, to make it work in general!
+ 1
@vrintle
Am not the questioner. May be wrong tag you added..!?
But In your sentence 9, $, - are also counted as words until especially said to ommit. Raw Words may contains any special chars and digits..
0
print(len(txt.split()))