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

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

提交回复
热议问题