[英]My program for counting how many vowels in a user input sentence doesn't count the same vowel twice. How do i fix this?
print ("Sentence analysis")
Sentence = (input("Please enter a sentence"))
def WordCount(Sentence):
words = (Sentence.count(' ')+1)
print ("There are", words ,"words in this sentence")
WordCount(Sentence)
The code above is fine and used to count how many words in the input sentence. 上面的代码很好,可以用来计算输入句子中有多少个单词。
vowels = ['a','e','i','o','u']
count=0
for v in vowels:
if v in Sentence:
count+=1
print (count)
When running, say if I input aaeiou
would only count 5 vowels whereas there are 6. How do I fix this? 跑步时,说如果我输入
aaeiou
只会数5个元音,而有6个元音。我该如何解决?
Use .count()
: 使用
.count()
:
count = 0
for v in vowels:
count += Sentence.count(v)
Or better: 或更好:
count = sum(Sentence.count(v) for v in vowels)
That is because you are doing your check in reverse. 那是因为您正在反向进行检查。 You want to go over your sentence and check each letter against vowels:
您想遍历句子并针对元音检查每个字母:
vowels = ['a','e','i','o','u']
count=0
for s in Sentence:
if s in vowels:
count+=1
print (count)
For a nicer approach, however, check out @zondo's answer. 对于更好的方法,请查看@zondo的答案。
The problem you are having is that when you loop through v
in vowels
and check if v
is in Sentence
it only checks if it v
is present in Sentance
not how many times. 您遇到的问题是,当您在
vowels
循环遍历v
并检查v
是否在Sentence
它仅检查v
在Sentance
是否存在了多少次。 If you flip it around so it checks through Sentence
first and check each letter to see if it is in vowels
it will check all of the letters in Sentence
. 如果将其翻转,则它将首先检查
Sentence
并检查每个字母是否在vowels
,它将检查Sentence
所有字母。
print ("Sentence analysis")
Sentence = (input("Please enter a sentence"))
vowels = ['a','e','i','o','u']
count=0
for letter in Sentence:
if letter in vowels:
count+=1
print (count)
For the first code can be simplified the WordCount()
function as: 对于第一个代码,
WordCount()
函数可以简化为:
print(len(Sentence.split()))
or: 要么:
import re
print(len(re.findall(r'\w+', Sentence)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.