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

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

    This is a simple word counter using regex. The script includes a loop which you can terminate it when you're done.

    #word counter using regex
    import re
    while True:
        string =raw_input("Enter the string: ")
        count = len(re.findall("[a-zA-Z_]+", string))
        if line == "Done": #command to terminate the loop
            break
        print (count)
    print ("Terminated")
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题