How to count the number of words in a sentence, ignoring numbers, punctuation and whitespace?

前端 未结 8 2057
礼貌的吻别
礼貌的吻别 2020-11-28 06:45

How would I go about counting the words in a sentence? I\'m using Python.

For example, I might have the string:

string = \"I     am having  a   very         


        
8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 07:41

    You can use regex.findall():

    import re
    line = " I am having a very nice day."
    count = len(re.findall(r'\w+', line))
    print (count)
    

提交回复
热议问题