Hoe tel je het aantal woorden in een zin, waarbij je cijfers, interpunctie en witruimte negeert?

Hoe zou ik de woorden in een zin moeten tellen? Ik gebruik Python.

Ik zou bijvoorbeeld de string kunnen hebben:

string = "I     am having  a   very  nice  23!@$      day. "

Dat zouden 7 woorden zijn. Ik heb problemen met het willekeurige aantal spaties na/voor elk woord en ook met cijfers of symbolen.


Antwoord 1, autoriteit 100%

str.split()zonder enige argumenten splitst op runs van witruimtetekens:

>>> s = 'I am having a very nice day.'
>>> 
>>> len(s.split())
7

Van de gelinkte documentatie:

Als sepniet is opgegeven of Noneis, wordt een ander splitsingsalgoritme toegepast: reeksen opeenvolgende witruimten worden beschouwd als een enkel scheidingsteken en het resultaat bevat geen lege tekenreeksen aan het begin of einde als de tekenreeks voorloop- of volgspaties heeft.


Antwoord 2, autoriteit 58%

U kunt regex.findall()gebruiken :

import re
line = " I am having a very nice day."
count = len(re.findall(r'\w+', line))
print (count)

Antwoord 3, autoriteit 7%

s = "I     am having  a   very  nice  23!@$      day. "
sum([i.strip(string.punctuation).isalpha() for i in s.split()])

De bovenstaande verklaring gaat door elk stuk tekst en verwijdert leestekens voordat wordt gecontroleerd of het stuk echt een reeks alfabetten is.


Antwoord 4, autoriteit 5%

Dit is een eenvoudige woordenteller met regex. Het script bevat een lus die u kunt beëindigen als u klaar bent.

#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")

Antwoord 5, autoriteit 5%

   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))  

uitvoer is 8


Antwoord 6, autoriteit 4%

Wat dacht je van het gebruik van een eenvoudige lus om het aantal spaties te tellen!?

txt = "Just an example here move along" 
count = 1
for i in txt:
if i == " ":
   count += 1
print(count)

Antwoord 7, autoriteit 3%

Ok, hier is mijn versie om dit te doen. Ik heb gemerkt dat u wilt dat uw uitvoer 7is, wat betekent dat u geen speciale tekens en cijfers wilt tellen. Dus hier is het reguliere patroon:

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

Waar [a-zA-Z_]betekent dat het overeenkomt met elkteken tussen a-z(kleine letters) en a-z(hoofdletters).


Over spaties. Als je alle extra spaties wilt verwijderen, doe dan gewoon:

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!

Antwoord 8

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)

Other episodes