简体   繁体   English

创建一个在文本中查找大写单词的映射器

[英]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.实现 filescounter,它接受任何类型的字符串并返回该字符串中大写单词的数量,包括最后一个和第一个字符。

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() .如果大写是指只需要大写第一个字母,那么您可以将word.isupper()替换为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 split() 通过空格或换行符将文本分割为单词
  • so called list comprehension works faster than an explicit for-loop and looks nicer所谓的列表理解比显式 for 循环工作得更快,看起来更好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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