簡體   English   中英

在Python中使用for循環計算字符串中的元音數量

[英]Counting the number of vowels in a string using for loops in Python

Python代碼:

sentence = input('Enter a string:')
vowel = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for vowel in sentence:
   Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

我正在嘗試編寫一個程序,提示用戶輸入字符串。 然后,程序返回字符串中的元音數量。 但是,該代碼僅返回字母數,而不考慮僅返回元音。

您已經定義了一個元音字符串,但是正在循環中重新定義變量元音。

我建議定義一set元音,然后基於if檢查增加您的計數器。

vowels = set('aeiou')  

counter = 0
for c in sentence.lower():
    if c in vowels:
        counter += 1

在這里,如果c是元音(即c屬於存儲在vowels中的vowels集合),則元音中的if c in vowels將返回True


您可以使用collections.Counter對象改進此解決方案:

from collections import Counter

c = Counter(sentence.lower())
counter = sum(c[v] for v in set('aeiou'))

或者,您可以使用list comprehension並計算其長度。

我認為最好的方法是使用簡單的RegEx。 匹配元音的RegEx為[aeiou] (如果您也想匹配“ y”,則為[aeiouy] )。

您可以使用re.findall查找句子中所有元音的出現,使用re.IGNORECASE標志忽略大小寫。

>>> import re
>>> sentence = "my name is Jessica"
>>> len(re.findall(r'[aeiou]', sentence, flags=re.IGNORECASE))
6

該解決方案的優點是您可以輕松擴展它以添加重音字符或其他unicode字符:

>>> import re
>>> sentence = "Dès Noël où un zéphyr haï me vêt de glaçons würmiens je dîne d’exquis rôtis de bœuf au kir à l’aÿ d’âge mûr & cætera !"
>>> len(re.findall(r'[aeiouyàâèéêëiïîöôüûùæœÿ]', sentence, flags=re.IGNORECASE))
41

您不會在任何地方檢查句子中的字母是否是元音。 for x in y:的語法for x in y:在一個可迭代對象(字符串,列表等)上定義一個循環,其中對於每次循環迭代,變量x均設置為該可迭代對象的下一個元素。

for vowel in sentence:for vowel in sentence:僅定義了一個循環,其中將vowel分配給輸入句子的每個字母。 您先前的vowel = ...聲明vowel = ...在這里無效。

達到預期效果的不錯的1缸套將是:

sentence = input('Enter a string:')
vowels = 'aeiou'
count = len([c for c in sentence.lower() if c in vowels])

發生這種情況是因為您不驗證字母是否是元音。 當您在for循環上放置“句子中的元音”時,您將覆蓋元音中的內容,而元音將成為每次循環迭代時句子中的每個字母。

sentence = input('Enter a string:')
vowel = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for letter in sentence:
  if letter in vowel.split(','):
    Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

使用python 3:

sentence = input('Enter a string:')
vowels = 'A,a,E,e,I,i,O,o,U,u'
Count = 0
for each_char in sentence:
    if each_char in vowels:
        Count += 1 
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

這是我使用集合計數器的代碼

import collections
vowel = ['a', 'e', 'i', 'o', 'u']
count = 0

sentence = input('Enter a string:').lower()
counter = collections.Counter(sentence)
for word in counter:
    if word in vowel:
        count += counter[word]

print('There are {} vowels in the string: \'{}\''.format(count,sentence))
sentence = input('Enter a string:')
Count = 0
for eachLetter in sentence:
    if eachLetter.lower() in ['a','e','i','o','u']:
        Count += 1
print('There are {} vowels in the string: \'{}\''.format(Count,sentence))

我們只需要列表中的小寫元音,因為僅使用.lower()即可將句子變成小寫

然后,我們遍歷每個元音,並使用.count()計數在句子中找到多少個每個元音。 然后,我們匯總總計數,直到得出元音總數。

sentence = 'This is a sentence'
vowels = ['a','e','i','o','u']
Count = 0
for vowel in vowels:
    Count = Count + sentence.lower().count(vowel)

即使有for循環約束,也無需為此加難:

VOWELS = 'aeiou'

sentence = input('Enter a string: ')

count = 0

for letter in sentence.lower():
    count += letter in VOWELS

print('There are {} vowels in the string: \'{}\''.format(count, sentence))

其核心是布爾值也是我們可以求和的數字。 如果要處理大量文本並需要提高效率,可以將VOWELS set('aeiou')set('aeiou') 我們可以用生成器表達式替換count初始化和for循環:

count = sum(1 for c in sentence.lower() if c in VOWELS)

這可能比列表理解更好,因為它不會創建一次性列表,並且避免了第二次處理字母的子集。

暫無
暫無

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

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