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

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

    Ok here is my version of doing this. I noticed that you want your output to be 7, which means you dont want to count special characters and numbers. So here is regex pattern:

    re.findall("[a-zA-Z_]+", string)
    

    Where [a-zA-Z_] means it will match any character beetwen a-z (lowercase) and A-Z (upper case).


    About spaces. If you want to remove all extra spaces, just do:

    string = string.rstrip().lstrip() # Remove all extra spaces at the start and at the end of the string
    while "  " in string: # While  there are 2 spaces beetwen words in our string...
        string = string.replace("  ", " ") # ... replace them by one space!
    

提交回复
热议问题