簡體   English   中英

Python,從輸入的字符串開始計數。 需要按特定順序退貨嗎?

[英]Python, counting from an inputted string. Needs to be returned in a specific order?

因此,我正在輸入用戶需要輸入>> Count('bla bla bla')的代碼,程序需要在bla bla bla短語中計數,並以此特定順序返回單詞及其計數。

有幫助嗎?

您的count功能使用不正確。 您想要text.search(vowel) ,而不是vowel.search(text)

>>> s = 'this is some string with a lot of vowels'
>>> vowels = 'aeiou'
>>> {i : s.count(i) for i in vowels}
{'a': 1, 'i': 4, 'e': 2, 'u': 0, 'o': 4}

字典沒有順序,因此如果要按元音順序計數:

>>> [(i,s.count(i)) for i in vowels]
[('a', 1), ('e', 2), ('i', 4), ('o', 4), ('u', 0)]
def vowelCount(text):
    vowels = 'aeiou'
    return ("a, e, i, o, and u appear, respectively, %s times." %", ".join([ str(text.count(x)) for x in vowels]))

print vowelCount('bla bla bla')

希望這可以幫助。

您輸入錯誤:

def vowelCount(text):
    vowels = 'aeiou'
    counts = {x:text.count(x) for x in vowels}
    keys = counts.keys()
    values = counts.values()
    return ','.join(keys[:-1]) + ' and '+ keys[-1] +' appear, respectively, '+ ','.join(str(v) for v in values)+' times.'

編寫的代碼甚至根本不檢查輸入文本。 您正在計算每個元音出現在vowels

替換為text.count(i)而不是vowels.count(i)

暫無
暫無

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

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