簡體   English   中英

創建一個在文本中查找大寫單詞的映射器

[英]Creating a mapper that find the capitalized words in a text

實現 filescounter,它接受任何類型的字符串並返回該字符串中大寫單詞的數量,包括最后一個和第一個字符。

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

我被困在如何解決這個問題上。

在空白處拆分文本,然后遍歷單詞:

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

如果大寫是指只需要大寫第一個字母,那么您可以將word.isupper()替換為word[0].isupper()

用這個:

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

解釋:

  • split() 通過空格或換行符將文本分割為單詞
  • 所謂的列表理解比顯式 for 循環工作得更快,看起來更好

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM