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

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

    import string 
    
    sentence = "I     am having  a   very  nice  23!@$      day. "
    # Remove all punctuations
    sentence = sentence.translate(str.maketrans('', '', string.punctuation))
    # Remove all numbers"
    sentence = ''.join([word for word in sentence if not word.isdigit()])
    count = 0;
    for index in range(len(sentence)-1) :
        if sentence[index+1].isspace() and not sentence[index].isspace():
            count += 1 
    print(count)
    

提交回复
热议问题