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

前端 未结 8 2042
礼貌的吻别
礼貌的吻别 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:26

    s = "I     am having  a   very  nice  23!@$      day. "
    sum([i.strip(string.punctuation).isalpha() for i in s.split()])
    

    The statement above will go through each chunk of text and remove punctuations before verifying if the chunk is really string of alphabets.

提交回复
热议问题