简体   繁体   中英

Creating a mapper that find the capitalized words in a text

Implement filescounter, which takes a string in any variety and returns the number of capitalized words in that string, inclusive of the last and first character.

def filescounter(s):
    sr=0
    for words in text:
        #...
    return sr

I'm stuck on how to go about this.

Split the text on whitespace then iterate through the words:

def countCapitalized(text):
    count = 0
    for word in text.split():
        if word.isupper():
            count += 1
    return count

If, by capitalized, you mean only the first letter needs to be capitalized, then you can replace word.isupper() with word[0].isupper() .

Use this:

def count_upper_words(text):
    return sum(1 for word in text.split() if word.isupper())

Explanation:

  • split() chops text to words by either spaces or newlines
  • so called list comprehension works faster than an explicit for-loop and looks nicer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM