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

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

        def wordCount(mystring):  
            tempcount = 0  
            count = 1  
    
            try:  
                for character in mystring:  
                    if character == " ":  
                        tempcount +=1  
                        if tempcount ==1:  
                            count +=1  
    
                        else:  
                            tempcount +=1
                     else:
                         tempcount=0
    
                 return count  
    
             except Exception:  
                 error = "Not a string"  
                 return error  
    
        mystring = "I   am having   a    very nice 23!@$      day."           
    
        print(wordCount(mystring))  
    

    output is 8

提交回复
热议问题